MYSQLi INSERT


We learned to create a database, a data table, then this section tells you to add data to the table:

Here are some grammar rules:

· SQL query statements in PHP must use quotes

· String values ​​in SQL query statements must be quoted

· Values ​​do not require quotes

· NULL values ​​do not require quotes

The INSERT INTO statement is typically used to add new records to a MySQL table

Grammar 

INSERT INTO table_name (column1, column2, column3,...) VALUES  (value1, value2, value3,...)
Table_name : the name of the table we want to insert data into that table
Column1 , column2 : the fields in the table, such as id firstname
Value1 , value2 : is the data we want to insert
Note 

1. You can not specify the field name column..., but the order after values ​​should be the same as the order of the table fields. Insert into user(username,sex) values('Liu Qi', 1);

2. The field with the default value can be left unwritten, which is the default value.

3. If there is a default value or a nullable field does not want to pass in a specific value, you can write null.

To learn more about SQL, check out our SQL tutorial.

Let us illustrate with examples:

Instance

In the previous chapters we have created the table "MyGuests", the table fields are: "id", "firstname", "lastname", "email" and "reg_date". Now let's start filling the table with data.

Note : If the column is set to AUTO_INCREMENT (such as "id" column) or TIMESTAMP (such as "reg_date" column), we do not need to specify a value in the SQL query statement; MySQL will automatically add a value to the column.

The meaning of AUTO_INCREMENT is that you will add data.

 Header("Content-type:text/html;charset=utf-8"); //Set the encoding
 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "test";
 
 // Create a connection
 $conn = mysqli_connect($servername, $username, $password, $dbname);
 / / Check the connection
 If (!$conn) {
     Die("Connection failed: " . mysqli_connect_error());
 }
 
 $sql = "INSERT INTO MyGuests (firstname, lastname, email)
 VALUES ('John', 'Doe', 'john@example.com')";
 
 If (mysqli_query($conn, $sql)) {
     Echo "New record inserted successfully";
 } else {
     Echo "Error: " . $sql . "
" . mysqli_error($conn);
 }
 
 Mysqli_close($conn);
 
 
New record inserted successfully

Let's open PHPadmin and see if there is data we added:
 
Can see that we have inserted the data into our data table


Last Updated: 2018-07-06 12:32:44 By akshay

SHARE THIS

share_facebook share_twitter share_google_plus

Please Comment Here :