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);
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
// 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
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
// 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
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
// 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
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
// 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
एक 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
// 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
- इस गलत मान्यता पर कि AJAX-submitted data किसी तरह एक regular form के data से कम risky है, एक AJAX endpoint की database query के लिए prepared statements skip करना।
- बिना किसी connection reuse strategy के हर single AJAX request पर एक नया database connection खोलना, जो heavy traffic के तहत unnecessary overhead add कर सकता है।
- 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 किया जाना चाहिए।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: