Skip to content

PHP mySQL PDO guideΒΆ

When coding in PHP, there are a few coding examples of how to securely connect to a database.

// Connect to the database
$dbi = new PDO('mysql:host=localhost;port=3306;dbname=databse',$username,$password, [ PDO::ATTR_PERSISTENT => true ]);

// Return multiple records
$sql = "SELECT * FROM myTable";
$sth = $dbi->prepare($sql);
$sth->execute();
$data = $sth->fetchAll();

// Read a single record
$sql = "SELECT * FROM myTable WHERE id = :id";
$sth = $dbi->prepare($sql);
$sth->execute(['id' => $id]);
$data = $sth->fetchAll()[0];

// Delete an entry from a table
$sql = "DELETE FROM myTable WHERE id = :id";
$sth = $dbi->prepare($sql);
$sth->execute([ 'id' => $id ]);