PHP INSERT
The PHP INSERT statement is used to insert data into a database table. This statement is part of the CRUD (Create, Read, Update and Delete) operation of a database.
Syntax
The basic syntax of the INSERT statement is as follows:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example
Consider a table named "students" with columns "id", "name", "age" and "address". The following PHP code helps to insert data into the "students" table.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert data into 'students' table
$sql = "INSERT INTO students (name, age, address)
VALUES ('John Doe', '25', 'New York')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Output
The above PHP code will output the following message if the data is successfully inserted into the database:
New record created successfully
Explanation
- First, establish a connection to the MySQL server using mysqli_connect() function and instantiate a new mysqli() object.
- Then, define an SQL statement to insert data into the database using the INSERT INTO statement.
- In this particular example, we are inserting a new record into the "students" table with the following values: Name - "John Doe", Age - "25", Address - "New York".
- Finally, we used the mysqli_query() function to execute the SQL statement and check the result with the if statement.
Use
The INSERT statement is used to insert data into a database table. It is used when creating a new record in the database.
Important Points
- Before executing the INSERT statement, you must establish a connection to the MySQL server.
- Make sure that the column names and values you are inserting follow the correct data type of the table's columns.
- Avoid inserting data directly from user input without validating and sanitizing it first to prevent SQL injection attacks.
Summary
- The PHP INSERT statement is used to insert data into a database table.
- The basic syntax of the INSERT statement includes the table name, columns, and values.
- The mysqli_query() function is used to execute the SQL statement, and the result is checked using the if statement.
- Always validate and sanitize user input before inserting data into the database.