How to Insert Data Into MySQL Database Table Using PHP?

Today, We want to share with you insert data in mysql using php form.In this post we will show you how to insert data in mysql using php?, hear for how we can update and delete data using Delete and Update statements. we will give you demo and example for implement.In this post, we will learn about How to Insert and Retrieve Data in Database? with an example.

how to insert multiple rows in mysql using php form?

For insert data in MySQL first i have to make a table in mysql data base.

Here we using 3 main useful file for insert data in MySQL:

  • database.php:For connecting data base in Mysql
  • do_insert_product.php:for getting the values from the user
  • save_products_data.php:A PHP file that all products save the request

database Structure

CREATE TABLE `products` (
	`userid` int(8) NOT NULL,
	`product_code` varchar(55) NOT NULL,
	`product_name` varchar(55) NOT NULL,
	`product_desc` varchar(55) NOT NULL,
	`price` varchar(50) NOT NULL


$dbname = "crud";
   die('Could not Connect My Sql:' .mysql_error());


<!DOCTYPE html>
	<form method="post" action="save_products_data.php">
		Product Code:<br>
		<input type="text" name="product_code">
		Product Name:<br>
		<input type="text" name="product_name">
		Product Desc:<br>
		<input type="text" name="product_desc">
		Product Price:<br>
		<input type="text" name="price">
		<input type="submit" name="save" value="submit">


include_once 'database.php';
	 $product_code = $_POST['product_code'];
	 $product_name = $_POST['product_name'];
	 $product_desc = $_POST['product_desc'];
	 $price = $_POST['price'];
	 $sql = "INSERT INTO products (product_code,product_name,product_desc,price)
	 VALUES ('$product_code','$product_name','$product_desc','$price')";
	 if (mysqli_query($conn, $sql)) {
		echo "New record created successfully !";
	 } else {
		echo "Error: " . $sql . "
" . mysqli_error($conn);

Alternative Code in (PDO)

$dbname = "products_list";
try {
    $product_code = $_POST['product_code'];
    $product_name = $_POST['product_name'];
    $product_desc = $_POST['product_desc'];
    $price = $_POST['price'];
    $insertdate = date("Y-m-d H:i:s");
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
   $sql = "INSERT INTO products (product_code,product_name,product_desc,price,datetime)
    VALUES ('$product_code', '$product_name','$product_desc','$price','$insertdate')";
    echo "New record created successfully";
catch(PDOException $e)

    	echo $sql . "<br>" . $e->getMessage();

$conn = null;

I hope you get an idea about insert data in mysql using php api.
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.