Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to insert a row into a database

Short answer

Pass the values separately from the query — in execute():

<?php
 
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');
 
$statement = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
$statement->execute(['name' => 'Anna', 'email' => 'anna@example.com']);
 
echo $pdo->lastInsertId();

Output:

1

Several rows

One prepared statement is run in a loop:

<?php
 
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE tags (id INTEGER PRIMARY KEY, title TEXT)');
 
$statement = $pdo->prepare('INSERT INTO tags (title) VALUES (?)');
 
foreach (['php', 'sql', 'css'] as $title) {
    $statement->execute([$title]);
}
 
echo $pdo->query('SELECT COUNT(*) FROM tags')->fetchColumn();

Output:

3

Functions used in this recipe

  • PDOStatement — A prepared statement and its result.
  • PDO — A database connection.

Thanks for reading!

Donate to the site — we work hard for you.