PHP MySQL Insert Data
In this page:
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if (!mysqli_query($conn, $sql)) {
echo "Error: " . mysqli_error($conn);
}
Basic INSERT Statement
INSERT INTO tableName (column1, column2) VALUES (value1, value2) एक table में एक नया row add करता है, explicitly नाम बताते हुए कि कौन सी columns कौन सी values receive करेंगी -- list न की गई कोई भी column automatically अपनी default value (या NULL) पाती है।
उदाहरण: Basic INSERT Statement
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (id INTEGER, name TEXT, email TEXT)");
$db->exec("INSERT INTO users (name, email) VALUES ('Alice', '[email protected]')");
// Print "Row inserted" to the output
echo "Row inserted";
?>
Login to try C/C++/Java/PHP code in the editor
Prepared Statements से Data Safely Insert करना
जब insert की जा रही values user input से आती हैं, एक prepared statement -- mysqli_prepare(), bound placeholders, और mysqli_stmt_execute() से बनाया गया -- SQL injection रोकने के लिए ज़रूरी है, क्योंकि database bound values को पूरी तरह data की तरह treat करता है, कभी SQL command का हिस्सा नहीं।
उदाहरण: Inserting Data Safely with Prepared Statements
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT, email TEXT)");
// Declare `$stmt`, set to `$db->prepare("INSERT INTO users (name, email) VALUES (:name, :email)")`
$stmt = $db->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindValue(':name', $_POST['name'] ?? 'Alice', SQLITE3_TEXT);
$stmt->bindValue(':email', $_POST['email'] ?? '[email protected]', SQLITE3_TEXT);
$stmt->execute();
// Print "Inserted safely from user input" to the output
echo "Inserted safely from user input";
?>
Login to try C/C++/Java/PHP code in the editor
Check करना कि एक Insert Succeed हुआ या नहीं
mysqli_query() अगर statement successfully execute हो तो true return करता है और fail हो तो false -- इस return value को check करना, और fail होने पर mysqli_error() पढ़ना, reliably यह जानने के लिए ज़रूरी है कि एक row actually save हुआ या नहीं।
उदाहरण: Checking Whether an Insert Succeeded
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT)");
// Declare `$result`, set to `$db->exec("INSERT INTO users (name) VALUES ('Alice')")`
$result = $db->exec("INSERT INTO users (name) VALUES ('Alice')");
// Print `$result ? "Insert succeeded" : "Insert failed: " . $db->lastErrorMsg()` to the output
echo $result ? "Insert succeeded" : "Insert failed: " . $db->lastErrorMsg();
?>
Login to try C/C++/Java/PHP code in the editor
Special Characters वाला Data Insert करना
Apostrophes, quotes, या दूसरे special characters वाले text को raw SQL में careful handling चाहिए -- "O'Brien" जैसे किसी name में एक un-escaped apostrophe एक manually built query string तोड़ देगा, जो एक और वजह है कि prepared statements (जो इसे automatically handle करते हैं) safer default हैं।
उदाहरण: Inserting Data with Special Characters
<?php
// 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', "O'Brien", SQLITE3_TEXT);
$stmt->execute();
// Print "Apostrophe handled safely by the prepared statement" to the output
echo "Apostrophe handled safely by the prepared statement";
?>
Login to try C/C++/Java/PHP code in the editor
एक Row Insert करना और तुरंत उसका Data इस्तेमाल करना
एक common pattern है एक नया row insert करना और फिर तुरंत उस अभी-अभी saved data के साथ कुछ करना, जैसे एक confirmation message दिखाना या नए record को दिखाने वाले एक page पर redirect करना -- insert के लिए इस्तेमाल किए गए वही $name और $email variables बस बाद में reuse हो जाते हैं।
उदाहरण: Inserting a Row and Using Its Data Immediately
<?php
// Declare `$name`, set to "Alice"
$name = "Alice";
// Declare `$email`, set to "[email protected]"
$email = "[email protected]";
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT, email TEXT)");
// Declare `$stmt`, set to `$db->prepare("INSERT INTO users (name, email) VALUES (:name, :email)")`
$stmt = $db->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindValue(':name', $name, SQLITE3_TEXT);
$stmt->bindValue(':email', $email, SQLITE3_TEXT);
$stmt->execute();
// Print "Saved $name ($email)! Confirmation sent." to the output
echo "Saved $name ($email)! Confirmation sent.";
?>
Login to try C/C++/Java/PHP code in the editor
- raw user input को सीधे SQL string में concatenate करके एक INSERT query बनाना, जो SQL injection का दरवाज़ा खोलता है -- इसके बजाय prepared statements इस्तेमाल किए जाने चाहिए।
- एक INSERT statement में columns और values की संख्या या order mismatch करना, जो या तो पूरी तरह fail हो जाता है या चुपचाप data को गलत columns में insert कर देता है।
- mysqli_query() का return value check करना भूल जाना, एक failed insert (जैसे एक constraint violation) को miss करते हुए जो actually table में कभी पहुँचा ही नहीं।
- INSERT INTO table (col1, col2) VALUES (val1, val2) named columns में दी गई values के साथ एक नया row add करता है।
- raw variables से insert की गई values को हमेशा bound parameters वाले एक prepared statement से गुज़रना चाहिए, कभी direct string concatenation से नहीं।
- mysqli_query() एक successful insert पर true return करता है और failure पर false -- row saved होने की उम्मीद रखने से पहले हमेशा यह check करें।
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- PHP MySQL Introduction
- PHP MySQLi Connection
- PHP PDO Introduction
- PHP CRUD Operations
- PHP Prepared Statements
- PHP Stored Procedures
- PHP Transactions
- PHP Error Handling in DB
- PHP MySQL Connect
- PHP MySQL Create DB
- PHP MySQL Create Table
- PHP MySQL Insert Data
- PHP MySQL Get Last ID
- PHP MySQL Insert Multiple
- PHP MySQL Prepared Statements
- PHP MySQL Select Data
- PHP MySQL Where
- PHP MySQL Order By
- PHP MySQL Delete Data
- PHP MySQL Update Data
- PHP MySQL Limit Data