PHP Code Examples

Insert Data into MySQL with PHP PDO

Insert submitted values safely with a prepared statement and retrieve the newly created record ID.

Example

<?php
$title = trim($_POST['title'] ?? '');
$body = trim($_POST['body'] ?? '');

if ($title === '' || $body === '') {
    http_response_code(422);
    exit('Title and body are required.');
}

$sql = 'INSERT INTO articles (title, body) VALUES (:title, :body)';
$stmt = $pdo->prepare($sql);
$stmt->execute([
    'title' => $title,
    'body' => $body,
]);

$newArticleId = (int) $pdo->lastInsertId();

Explanation

Placeholders keep values separate from SQL syntax. This helps prevent SQL injection and makes the query easier to maintain.

Remember

Prepared statements protect values, not SQL identifiers. If a column name or sort direction must be dynamic, choose it from a strict server-side allowlist.

Share this page Help other developers discover this resource.