← Back to PHP Course | Chapter 15: Web Development | Lesson 10 of 12

PHP AJAX Database

कई AJAX requests specifically database में data पढ़ने या लिखने के लिए exist करती हैं -- comments की एक live list fetch करना, एक नया task save करना, एक status update करना -- पहले cover हुई हर चीज़ combine करते हुए: AJAX request पढ़ना, एक database query चलाना (safely, prepared statements के साथ), और result को JSON की तरह return करना।
Syntax
php
$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);

AJAX के लिए Database से Data Fetch करना

एक read-only AJAX endpoint एक SELECT query चलाता है और results को JSON की तरह return करता है -- एक database SELECT (जैसा MySQL topics में covered) को json_encode() के साथ combine करके एक ऐसा response produce करते हुए जिसे JavaScript directly usable data में parse कर सके।

उदाहरण: Fetching Data from a Database for AJAX

php
<?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);
?>

AJAX-Submitted Data को Database में Save करना

एक write AJAX endpoint submitted data पढ़ता है (आमतौर पर $_POST से), इसे validate करता है, और एक prepared statement इस्तेमाल करके database में insert या update करता है -- exactly वही safe pattern जो पहले regular form submissions के लिए covered हुआ, बस इसके बजाय एक AJAX call से triggered।

उदाहरण: Saving AJAX-Submitted Data to a Database

php
<?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"]);
?>

Database Errors को Safely Handle करना

एक AJAX endpoint में एक failed database query को server-side log किया जाना चाहिए (real error detail के साथ) लेकिन client को सिर्फ एक generic, non-revealing message के साथ report किया जाना चाहिए -- raw database error text expose करना database के structure के बारे में sensitive information किसी को भी leak कर सकता है जो network requests inspect करे।

उदाहरण: Handling Database Errors Safely

php
<?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"]);
}
?>

Requests में एक Database Connection Reuse करना

हर AJAX request एक अलग HTTP request है, और PHP आमतौर पर हर एक के लिए एक fresh database connection खोलता है (क्योंकि PHP scripts default रूप से requests के बीच state persist नहीं करतीं) -- persistent connections (mysqli_pconnect() या PDO का persistent option) heavy, repeated AJAX traffic के तहत इस overhead को कम कर सकते हैं।

उदाहरण: Reusing a Database Connection Across Requests

php
<?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";
?>

एक Complete AJAX Database Endpoint Example

हर piece को साथ लाना: एक endpoint AJAX-submitted data पढ़ता है, इसे validate करता है, एक safely parameterized query चलाता है, किसी भी database error को gracefully handle करता है, और एक consistent JSON response return करता है -- database को छूने वाले ज़्यादातर AJAX endpoints के पीछे का पूरा realistic pattern।

उदाहरण: A Complete AJAX Database Endpoint Example

php
<?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"]);
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. इस गलत मान्यता पर कि AJAX-submitted data किसी तरह एक regular form के data से कम risky है, एक AJAX endpoint की database query के लिए prepared statements skip करना।
  2. बिना किसी connection reuse strategy के हर single AJAX request पर एक नया database connection खोलना, जो heavy traffic के तहत unnecessary overhead add कर सकता है।
  3. AJAX response में सीधे raw database error messages return करना, potentially client को sensitive schema या configuration details leak करते हुए।
चैप्टर सारांश
  • database को छूने वाला एक AJAX endpoint किसी भी PHP database script जैसा ही pattern follow करता है: connect, prepare, execute, fetch, respond।
  • Prepared statements AJAX-submitted data के लिए उतने ही ज़रूरी हैं जितने एक regular form के लिए, क्योंकि दोनों equally untrusted user input हैं।
  • Database errors को server-side log किया जाना चाहिए लेकिन client को एक generic, non-revealing error message की तरह return किया जाना चाहिए।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.