Insert data into MySQL database using PHP
In order to insert data in database tables, you firstly need to be familiar with basic SQL queries.Here we are going to see the basic INSERT query before starting PHP codings.
INSERT QUERY:
INSERT INTO table_name (column_name 1, column_name 2, column_name 3 . . . . . . . . ) VALUES (‘value 1’, ‘value2’, ‘value3 ’ . . . . . . . . .);
The above query is the important key factor for this operation.
Establish the MySQL Database connection first, I have given a connection tutorial before, if you want to learn the connection, click here
Establish the MySQL Database connection first, I have given a connection tutorial before, if you want to learn the connection, click here
CREATE TABLE IN DATABASE:
First of all, open the browser and go to “localhost/phpmyadmin”. In PhpMyAdmin, create a new table under your database by clicking the “new” under your database name on the left side of the page.
Let us assume our table name is “USERS”.
Fill all the field names, data types, sizes, attributes and indexes fields and click save.
Fill all the field names, data types, sizes, attributes and indexes fields and click save.
USERS
ID | NAME | COUNTRY | |
---|---|---|---|
This is the example table you have created using phpmyadmin. Now it has no rows, we are going to insert values into this table.
WRITE THE INSERTION CODE IN PHP.
In order to perform any database operations, you have to be familiar with a function mysqli_query().Mysqli_query()
mysqli_query() is a PHP function used to execute a SQL query in the MySQL database.
Syntax:
mysqli_query(connection_variable, sql_query);
mysqli_query(connection_variable, sql_query);
$connection_variable : The variable you have stored the MySQL connection ($conn).
Example:
$conn = mysqli_connect($host, $user, $password, $db);
$sql_query : The insert or any query you are going to perform.
Example:
$sql_query = “INSERT INTO USERS ( id, name, email, country) VALUES(‘ 3567’, ‘Robert ’, ‘rob@example.com’, ’USA’);”;
mysqli_query($conn, $sql_query);
Example:
$conn = mysqli_connect($host, $user, $password, $db);
$sql_query : The insert or any query you are going to perform.
Example:
$sql_query = “INSERT INTO USERS ( id, name, email, country) VALUES(‘ 3567’, ‘Robert ’, ‘rob@example.com’, ’USA’);”;
mysqli_query($conn, $sql_query);
The output of the table would look like this,
ID | NAME | COUNTRY | |
---|---|---|---|
3567 | Robert | rob@example.com | USA |
0 comments: