PHP Insert Data Into MySQL
After a database and a table have been created, we can start adding data in them.
- The SQL query must be quoted in PHP
- String values inside the SQL query must be quoted
- Numeric values must not be quoted
- The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
The following examples add a new record to the "Student" table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "data";
// Create connection$conn = new mysqli($servername, $username, $password, $dbname);
// Check connectionif ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Student(name, lastname, rollno)
VALUES ('Ram', 'Sharma', '12256')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
PHP Insert Multiple Records Into MySQL
Multiple SQL statements must be executed with the mysqli_multi_query() function.
The following examples add three new records to the "Student" table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "data";
// Create connection$conn = new mysqli($servername, $username, $password, $dbname);
// Check connectionif ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Student (name, lastname, rollno)
VALUES ('Ankit', 'Bhardwaj', '858');";
$sql .= "INSERT INTO Student (name, lastname, rollno)
VALUES ('Ashish', 'Rajput', '852');";
$sql .= "INSERT INTO Student (name, lastname, rollno)
VALUES ('Rahul', 'Paswan', '835')";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
No comments