PHP MySQL insert Query Syntax into the Table with MySQLi Example Code

PHP Insert Data Into MySQL

To insert a data in the MySQL database you have to use insert query.

In other words Insert is used to add new records.

Important points

  • The string must be quoted.
  • Numeric values must not be quoted.
  • The word NULL must not be quoted.

In the previous artical we created an empty table named “User” with five columns: “id”, “firstname”, “lastname”, “email_id” and “age”. Now, to fill the table with data.

Example – 1 Insert Data Into MySQL Example

`
  <?php
$server = "localhost";
$user = "root";
$password = "";
$dbname = "elex_tutorial";

// Create connection
$connection = mysqli_connect($server, $user, $password, $dbname);
// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO `User` (`firstname`, `lastname`, `email_id`, `age`)
VALUES ('John', 'Wattson', 'johnwattson66@redifmail.com', 50)";

if (mysqli_query($connection, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}

mysqli_close($connection);
?> 

In the above code, we insert data to the “User” table of “elex_tutorial” database. If the code run successfully then the output show a new record created successfully. So you have to check in the user table also.

You can leave a response, or trackback from your own site.
Leave a Reply to the article


Learn PHP

Learning & Certifications
Follow Us
Facebook Icon   Linked In Icon   Twitter Icon  
Validation and Recognition

Valid CSS! Valid HTML5!