i

PHP Tutorial

MySQL Commands-Inserting The data

Now, after creating the database and the table, we need to add data to the table. We use insert statement to add the rows into the table. The syntax of insert statement in MySQL is as below

INSERT INTO table_name( column1, column2, ..) values ( value1, value2, …)

The insert statement should be written in the php code as below:

$server_name = "localhost";
$username = "username";
$password = "password";
$db_name = "my_project";

// Create connection
$conn = new mysqli($server_name, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO visitors (name, email)
VALUES ('Sam', 'sam@example.com')";

if ($conn->query($sql) === TRUE) {
    echo "New record added successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

The record will be added with id automatically as 1 and the name and email values. If you want to check the last id you can echo the last inserted id of the record using insert_id.

You can also insert multiple records into MySQL using mysqli_multi_query() function.