Inserting Records via SQL Query in PHP
Let's now learn how to add new records
to a table. This is done using the
INSERT INTO
command. It has the following syntax:
<?php
$query = "INSERT INTO table (field1, field2...) VALUES (value1, value2...)";
?>
Let's add a new user to our users
table:
<?php
$query = "INSERT INTO users (name, age, salary) VALUES ('user', 30, 1000)";
?>
It might not be very obvious that the result
of the insertion does not need to be processed via mysqli_fetch_assoc
.
We just need to execute this query via
mysqli_query
, and the result of the insertion
should be checked via PhpMyAdmin:
<?php
$query = "INSERT INTO users (name, age, salary) VALUES ('user', 30, 1000)";
mysqli_query($link, $query) or die(mysqli_error($link));
?>
Also note that when inserting,
we do not specify the id
column and its value.
And this is correct, as the value of this column
will be set by the database automatically.
Add a new user 'user7'
, 26
years old, salary 300
.