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) adds a new row to a table, explicitly naming which columns receive which values -- any column not listed gets its default value (or NULL) automatically.
Example: 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
Inserting Data Safely with Prepared Statements
When the values being inserted come from user input, a prepared statement -- built with mysqli_prepare(), bound placeholders, and mysqli_stmt_execute() -- is essential to prevent SQL injection, since the database treats bound values purely as data, never as part of the SQL command itself.
Example: 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
Checking Whether an Insert Succeeded
mysqli_query() returns true if the statement executed successfully and false if it failed -- checking this return value, and reading mysqli_error() when it fails, is essential for reliably knowing whether a row was actually saved.
Example: 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
Inserting Data with Special Characters
Text containing apostrophes, quotes, or other special characters needs careful handling in raw SQL -- an un-escaped apostrophe in a name like "O'Brien" would break a manually built query string, which is yet another reason prepared statements (which handle this automatically) are the safer default.
Example: 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
Inserting a Row and Using Its Data Immediately
A common pattern is inserting a new row and then immediately doing something with the data that was just saved, like displaying a confirmation message or redirecting to a page showing the new record -- the same $name and $email variables used for the insert are simply reused afterward.
Example: 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
- Building an INSERT query by directly concatenating raw user input into the SQL string, which opens the door to SQL injection -- prepared statements should be used instead.
- Mismatching the number or order of columns and values in an INSERT statement, which either fails outright or silently inserts data into the wrong columns.
- Forgetting to check mysqli_query()'s return value, missing a failed insert (like a constraint violation) that never actually made it into the table.
- INSERT INTO table (col1, col2) VALUES (val1, val2) adds one new row with the given values into the named columns.
- Values inserted from raw variables should always go through a prepared statement with bound parameters, never direct string concatenation.
- mysqli_query() returns true on a successful insert and false on failure -- always check this before assuming the row was saved.
INSERT INTO is standard SQL, and running it through mysqli_query() or prepared statements works identically across all MySQL and MariaDB versions PHP supports.
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