Update.
On a second thought I think that to keep such an array with default settings would be a good idea. So it's better to make your class like
class MyPDO extends PDO
{
public function __construct($dsn, $username = NULL, $password = NULL, $options = [])
{
$default_options = [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
$options = array_merge($default_options, $options);
parent::__construct($dsn, $username, $password, $options);
}
public function run($sql, $args = NULL)
{
if (!$args)
{
return $this->query($sql);
}
$stmt = $this->prepare($sql);
$stmt->execute($args);
return $stmt;
}
}
But for the rest - I honestly cannot think of any improvement else.
Yes, you'll have to supply the connection credentials manually, but that's actually a good thing - it will make your class reusable. Just include it into another project and instantiate with different credentials! Or you can use another connection in the same project, if required.
So I would strongly suggest such a mini-extension only. Now to the code review.
//$db CREATE= TABLEnew queryMyPDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
# Table creation
$db->run>query("CREATE temporary TABLE tpdowrapper (
id int auto_increment primary key, name varchar(255))");
// INSERT# withPrepared gettingstatement insertmultiple idexecution
$id$stmt = $db->run>prepare("INSERT INTO tpdowrapper VALUES (NULL, ?)");
foreach (['Sam','Bob','Joe'] as $name)
{
$stmt->execute([$name]);
}
var_dump($db->lastInsertId());
//# singleGetting cellrows result.in usefula withloop
$stmt count= $db->run("SELECT * FROM pdowrapper");
while and($row such= $stmt->fetch(PDO::FETCH_LAZY))
{
echo $row['name'],",";
echo $row->name,",";
echo $row[1], PHP_EOL;
}
# Getting one row
$id = 1;
$row = $db->run("SELECT * FROM pdowrapper WHERE id=?", [$id])->fetch();
var_export($row);
# Getting single field value
$name = $db->run("SELECT name FROM tpdowrapper LIMITWHERE 1"id=?", [$id])->fetchColumn();
$count = $db->run("SELECT count(*) FROM t"pdowrapper")->fetchColumn();
var_export($name, $count);
//# one-dimensionalGetting array withof namesrows
$names$all = $db->run("SELECT name FROM t, LIMITid ?",FROM 10pdowrapper")->fetchAll(PDO::FETCH_COLUMNFETCH_KEY_PAIR);
var_export($all);
// calling
# aUpdate
$new stored= procedure'Sue';
$stmt = $db->run("call"UPDATE foo(pdowrapper SET name=?) WHERE id=?", $name);
$results =[$new, $stmt->fetchAll($id]);
var_dump($stmt->nextRowset>rowCount()); // clean the connection state
Other examples can be added on demandThe listing above is the actual working code that can be run as is.