if ($dbh != null) return $dbh;
$dbh = new PDO("mysql:dbname=NAME;host=127.0.0.1;charset=utf8;port=3306", 'root', '',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
return $dbh;
}
function db_getAll($table)
{
return db_getConnection()->query("SELECT * FROM {$table}")->fetchAll();
}
//$users = db_getAll('users');
function db_getById($table, $id)
{
return db_getConnection()->query("SELECT * FROM {$table} WHERE id={$id}")->fetch();
}
function db_insert($table, $arr)
{
$q = "INSERT INTO {$table}";
$fields = array_keys($arr);
$q .= "(" . implode(",", $fields) . ") VALUES (:" . implode(",:", $fields) . ")";
$stmt = db_getConnection()->prepare($q);
$stmt->execute($arr);
}
//for ($i=0;$i<100;$i++){
// db_insert('b_posts',[
// 'title'=>'post'.$i,
// 'body'=>'some text '.rand(0,800),
// 'user_id'=>rand(1,100)
// ]);
//}
function db_update($table, $id, $arr)
{
$id = (int)$id;
$q = "UPDATE {$table} SET ";
$fields = array_keys($arr);
$q .= implode("=?, ", $fields) . "=? WHERE id={$id}";
$stmt = db_getConnection()->prepare($q);
$stmt->execute(array_values($arr));
}
function db_delete($table, $id)
{
$id = (int)$id;
$stmt = db_getConnection()->query("DELETE FROM {$table} WHERE id={$id}");
}
function db_selectPage($table, $page, $cpp)
{
$page = (int)$page;
$cpp = (int)$cpp;
$offset = ($page - 1) * $cpp;
$q = "SELECT * FROM {$table} ORDER BY id DESC LIMIT {$cpp} OFFSET {$offset}";
$stmt = db_getConnection()->query($q);
return $stmt->fetchAll();
}
function db_count($table)
{
$q = "SELECT count(*) FROM {$table}";
$stmt = (int)db_getConnection()->query($q)->fetchColumn();
return $stmt;
}
function db_getByField($table,$field,$value){
return db_getConnection()->query("SELECT * FROM {$table} WHERE {$field}='{$value}' ")->fetch();
}
спасибо
Обсуждают сегодня