php-mysqlHow to insert data into a MySQL database using PHP?
Inserting data into a MySQL database using PHP is a common task. The following example code block shows how to do this:
<?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);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The output of this example code is:
New record created successfully
The code consists of the following parts:
- Setting up the connection to the MySQL database:
$servername
: The server name of the MySQL database.$username
: The username of the MySQL database.$password
: The password of the MySQL database.$dbname
: The name of the MySQL database.$conn
: The connection to the MySQL database.
- Writing the SQL query to insert data into the database:
$sql
: The SQL query to insert data into the database.
- Executing the SQL query:
$conn->query($sql)
: Executing the SQL query.
- Checking the result of the query:
if ($conn->query($sql) === TRUE)
: Checking if the query was successful.
- Closing the connection to the MySQL database:
$conn->close()
: Closing the connection to the MySQL database.
Helpful links
More of Php Mysql
- How to join tables with PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to create an SSL connection to MySQL using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to get the error message for a MySQL query using PHP?
- How to run multiple queries in PHP and MySQL?
- How to escape JSON in PHP and MySQL?
- How to get the last insert ID in PHP MySQL?
- How to get a single value from query in PHP MySQL?
- How to get the number of affected rows in a MySQL using PHP?
See more codes...