In this tutorial, we are going to learn how to insert the data into the MySQL database using php and there are two methods used to insert the data called MySQLi and pdo with examples.
$ads={1}
Now, we are using the INSERT INTO statement on the database table to insert the rows.
ok, Let's see, how they execute the SQL query using the INSERT INTO statement with values, after that passing the data using MySQLi in PHP function.
Ok, I already created the database and the table name student_details.
Read also:
How to use php pdo fetch class
php connect to mysql database
Activate and deactivate in php and mysql
How to filter table in active status in php
Database Table:
create table student_details
(
student_id int PRIMARY KEY AUTO_INCREMENT,
student_name varchar(255) not null,
class varchar(50) not null,
mobile_no varchar(25) not null
);
INSERT DATA USING PDO:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$hostname;dbname=student", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Database connection failed: " . $e->getMessage();
}
try{
$result = $conn->prepare("INSERT INTO student_details
(student_name,class,mobile_no) VALUES ('vicky', 9, 8796541233)");
$result->execute();
echo "Records inserted successfully.";
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
unset($conn);
?>
INSERT DATA USING MYSQLI:
<?php
$conn = new mysqli("localhost","root"," ","student");
if ($conn -> connect_errno) {
echo "Failed to connect to MySQL: " . $conn -> connect_error;
}
// Insert query execution
$result = "INSERT INTO student_details
(student_name,class,mobile_no) VALUES ('natalie', 9, 5796541233)";
if(mysqli_query($conn, $result)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($conn);
?>
In the above examples, we insert the new row of the student_details are added with specific values for the columns of student_name, class, and mobile_no and the student_id is an auto_increment so no need to add the value to the fields.
ok, I hope you will learn how to insert the data into the MySQL database using php and just copy the code and paste into your editor and run it with the local server.