PHP AJAX Database
In this page:
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE column = ?");
$stmt->execute([$value]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
header("Content-Type: application/json");
echo json_encode($rows);
Fetching Data from a Database for AJAX
A read-only AJAX endpoint runs a SELECT query and returns the results as JSON -- combining a database SELECT (as covered in the MySQL topics) with json_encode() to produce a response JavaScript can parse directly into usable data.
Example: Fetching Data from a Database for AJAX
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE products (name TEXT)");
$db->exec("INSERT INTO products VALUES ('Book'), ('Pen')");
// Declare `$result`, set to `$db->query("SELECT * FROM products")`
$result = $db->query("SELECT * FROM products");
// Declare `$rows` as an empty array
$rows = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) $rows[] = $row;
// Print `json_encode($rows)` to the output
echo json_encode($rows);
?>
Login to try C/C++/Java/PHP code in the editor
Saving AJAX-Submitted Data to a Database
A write AJAX endpoint reads submitted data (usually from $_POST), validates it, and inserts or updates it in the database using a prepared statement -- exactly the same safe pattern already covered for regular form submissions, just triggered by an AJAX call instead.
Example: Saving AJAX-Submitted Data to a Database
<?php
// Set `$_POST['name']` to "Alice"
$_POST['name'] = "Alice";
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT)");
// Declare `$stmt`, set to `$db->prepare("INSERT INTO users (name) VALUES (:name)")`
$stmt = $db->prepare("INSERT INTO users (name) VALUES (:name)");
$stmt->bindValue(':name', $_POST['name'], SQLITE3_TEXT);
$stmt->execute();
// Print `json_encode(["status" => "saved"])` to the output
echo json_encode(["status" => "saved"]);
?>
Login to try C/C++/Java/PHP code in the editor
Handling Database Errors Safely
A failed database query in an AJAX endpoint should be logged server-side (with the real error detail) but reported to the client with only a generic, non-revealing message -- exposing raw database error text can leak sensitive information about the database's structure to anyone inspecting network requests.
Example: Handling Database Errors Safely
<?php
// Try running this block; jump to `catch` if it throws
try {
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("SELECT * FROM nonexistent_table");
// Catch Exception $e
} catch (Exception $e) {
// Call `error_log($e->getMessage())`
error_log($e->getMessage());
// Print `json_encode(["status" => "error", "message" => "Something went wrong"])` to the output
echo json_encode(["status" => "error", "message" => "Something went wrong"]);
}
?>
Login to try C/C++/Java/PHP code in the editor
Reusing a Database Connection Across Requests
Each AJAX request is a separate HTTP request, and PHP typically opens a fresh database connection for each one (since PHP scripts do not persist state between requests by default) -- persistent connections (mysqli_pconnect() or PDO's persistent option) can reduce this overhead under heavy, repeated AJAX traffic.
Example: Reusing a Database Connection Across Requests
<?php
// mysqli_pconnect($host, $user, $pass, $db) or PDO's persistent option
$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_PERSISTENT => true]);
echo "Persistent connection reduces overhead under heavy AJAX traffic";
?>
Login to try C/C++/Java/PHP code in the editor
A Complete AJAX Database Endpoint Example
Bringing every piece together: an endpoint reads AJAX-submitted data, validates it, runs a safely parameterized query, handles any database error gracefully, and returns a consistent JSON response -- the full realistic pattern behind most AJAX endpoints that touch a database.
Example: A Complete AJAX Database Endpoint Example
<?php
// Set `$_POST['email']` to "[email protected]"
$_POST['email'] = "[email protected]";
// Check whether `!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)`
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// Print `json_encode(["status" => "error", "message" => "Invalid email"])` to the output
echo json_encode(["status" => "error", "message" => "Invalid email"]);
// Otherwise, run this branch
} else {
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE subscribers (email TEXT)");
// Declare `$stmt`, set to `$db->prepare("INSERT INTO subscribers (email) VALUES (:email)")`
$stmt = $db->prepare("INSERT INTO subscribers (email) VALUES (:email)");
$stmt->bindValue(':email', $_POST['email'], SQLITE3_TEXT);
$stmt->execute();
// Print `json_encode(["status" => "ok"])` to the output
echo json_encode(["status" => "ok"]);
}
?>
Login to try C/C++/Java/PHP code in the editor
- Skipping prepared statements for an AJAX endpoint's database query, on the mistaken assumption that AJAX-submitted data is somehow less risky than a regular form's.
- Opening a new database connection on every single AJAX request without any connection reuse strategy, which can add unnecessary overhead under heavy traffic.
- Returning raw database error messages directly in the AJAX response, potentially leaking sensitive schema or configuration details to the client.
- An AJAX endpoint that touches the database follows the same pattern as any PHP database script: connect, prepare, execute, fetch, respond.
- Prepared statements are just as essential for AJAX-submitted data as for a regular form, since both are equally untrusted user input.
- Database errors should be logged server-side but returned to the client as a generic, non-revealing error message.
mysqli and PDO database access work identically whether a PHP script is handling a full page load or an AJAX request.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: