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"));
1 Star2 Stars3 Stars4 Stars5 Stars

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

p.s. I increased my AdSense revenue by 68% using AI 🤖. Read my Ezoic review to find out how.

Leave a Reply

avatar
  Subscribe  
Notify of