PHP mysqli prepared statement insert example


MySQLi is the improved version of MySQL extension and it has more feature which is included in PHP Version 5.

The advantage using MySQLi is:

1. Prevent SQL Injection
2. Able to Prepare statement and bind params.
3. OOPS Interface and more.

In this tutorial you can learn how to insert values into the table using mysqli prepared statement.

First create a table, use the below SQL query:

-- Table structure for table `product`

  `prod_id` int(5) NOT NULL AUTO_INCREMENT,
  `prod_name` varchar(100) NOT NULL,
  `prod_code` int(6) NOT NULL,
  `prod_price` double NOT NULL,
  PRIMARY KEY (`prod_id`)

-- Dumping data for table `product`

Totally four fields in the above table with three different data types,

1. int
2. varchar
3. double

2. Here is the PHP script:


//connect to mysql server and select db
$mysqli = new mysqli( 'localhost', 'root', '', 'blog' );

//if connection failed show error
	echo "connect error: ". mysqli_connect_errno();

//check if the form is submitted

	//prepare statement
	$stmt = $mysqli->prepare( "insert into product (prod_name, prod_code, prod_price) values (?,?,?)" );

	//get values from form
	$prod_name 	= $_POST['prod_name'];
	$prod_code 	= $_POST['prod_code'];
	$prod_salary = $_POST['prod_salary'];

	//bind variable to the prepared statement
	$stmt->bind_param( "sid", $prod_name, $prod_code, $prod_salary );

	if( $stmt->execute() ){
		echo "Product Inserted";
	//close statement 


//close mysqli connection

<form action="" method="post">
			<td>Product Name:</td>
			<td><input type="text" name="prod_name" /></td>	
			<td>Product Code:</td>	
				<select name="prod_code">
			<td>Product Price:</td>	
			<td><input type="text" name="prod_salary" /></td>	
			<td><input type="submit"  /></td>	

The code is self explanatory, just read the comments.

If you already worked in other technologies such as Java or .Net you would know about prepared statement. But PHP developer not used this even though introduced long time back.

These are the steps you have follow:

1. prepare statement (?,?)
2. bind params with the proper data type

s - string
i - integer
d - double
b - blob

3. execute

2 thoughts on “PHP mysqli prepared statement insert example

Leave a Reply

Theme: Overlay by Kaira
%d bloggers like this: