INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
MySQL query using the INSERT INTO statement with appropriate values, after that we will execute this insert query through passing it to the PHP mysqli_query()
function to insert data in table. Here's an example,we created an empty table named "student_details" with five columns like stu_id, stu_name, college, email and mobile fields.
The following examples add a new record to the "student_details" table :
<?php
// Create connection
$ftl_connect = new mysqli("localhost", "root", "", "ftl_db");
// Check connection
if (!$ftl_connect) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO student_details (`stu_id`, `stu_name`, `college`, `email`, `mobile`)
VALUES ('', 'V V Ramana Reddy', 'S V Arts and Science College', 'info@freetimelearning.com', '9963666068')";
if (mysqli_query($ftl_connect, $sql)) {
echo "New record has successfully created..!";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($ftl_connect);
}
//Close Connection
mysqli_close($ftl_connect);
?>
<?php
// Create connection
$ftl_connect = new mysqli("localhost", "root", "", "ftl_db");
// Check connection
if ($ftl_connect->connect_error) {
die("Connection failed: " . $ftl_connect->connect_error);
}
$sql = "INSERT INTO student_details (`stu_id`, `stu_name`, `college`, `email`, `mobile`)
VALUES ('', 'V V Ramana Reddy', 'S V Arts and Science College', 'info@freetimelearning.com', '9963666068')";
if ($ftl_connect->query($sql) === TRUE) {
echo "New record has successfully created..!";
} else {
echo "Error: " . $sql . "<br>" . $ftl_connect->error;
}
//Close Connection
$ftl_connect->close();
?>
<?php
try {
$ftl_connect = new PDO("mysql:host=localhost;dbname=ftl_db", "root", "");
// set the PDO error mode to exception
$ftl_connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO student_details (`stu_id`, `stu_name`, `college`, `email`, `mobile`)
VALUES ('', 'V V Ramana Reddy', 'S V Arts and Science College', 'info@freetimelearning.com', '9963666068')";
// use exec() because no results are returned
$ftl_connect->exec($sql);
echo "New record has successfully created..!";
}
catch(PDOException $e)
{
echo $sql . "<br />" . $e->getMessage();
}
//Close Connection
$ftl_connect = null;
?>