How To insert Data in Php using PDO?
After a database and a table have been created,we can start inser records in it.
Here are some syntax you have to follow:
The SQL query must be in quoted
String values inside the SQL query must be in quoted except numeric value
id and create_at field we are not going to define because it is auto-increment and timestamp
use INSERT INTO statement to insert records
here a basic syntax of insert record:
INSERT INTO table_name (field1, field2, field3,...)
VALUES (data1, data2, data3,...)
In previous blog we created an empty table named "register" with sixcolumns: "id", "name", "email", "password" ,"mobile_no","create_at".
table Query:
CREATE TABLE `register` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL,
`password` varchar(15) NOT NULL,
`mobile_no` varchar(10) NOT NULL,
`create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
php Source Code:
<?php
$server = "localhost";
$username = "root";
$password = "";
$dbname = "demo1"; //database name
try {
$conn = new pdo("mysql:host=$server;dbname=$dbname",$username,$password);
$sql = "INSERT INTO register(name,email,password,mobile_no) VALUES('yash','yash123@gmail.com', 'yash123@', 9898989898)";
$conn->exec($sql);
echo "insert data successfully";
} catch (\Throwable $th) {
echo $sql . "<br>" . $th->getMessage();
}
$conn = null;
?>
you can also watch our video if you are not understand:
you can also watch our video if you are not understand:
No comments:
Post a Comment
If You have any doubt, or want to know about something, please let me know