Database connection in PHP with PDO example

Last updated on

Use the following PHP to connect to your MySQL database using PDO.

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password');

Replace localhost, testdb, username and password with your own details.

Select rows in a table

In this example we are going to select the firstname and lastname from a table called members.

foreach($db->query('SELECT * FROM members') as $row) {
    echo $row['firstname'].' '.$row['lastname'];

Insert rows into a table

Let’s insert a new record with firstname and lastname into a table called members.

$stmt = $db->prepare("INSERT INTO members(firstname,lastname) VALUES(:firstname,:lastname)");
$stmt->execute(array(':firstname' => 'Joe', ':lastname' => 'Smith'));

Update records

Let’s update the firstname of a record with the id of 33 in a table called members.

$stmt = $db->prepare("UPDATE members SET firstname=? WHERE id=?");
$stmt->execute(array("John", "33"));

Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.

Leave a reply

Your email address will not be published. Required fields are marked *