• PHP Video Tutorials

PHP mysqli_prepare() Function



Definition and Usage

The mysqli_prepare() function prepares an SQL statement for execution, you can use parameter markers ("?") in this query, specify values for them, and execute it later.

Syntax

mysqli_prepare($con, $str);

Parameters

Sr.No Parameter & Description
1

con(Mandatory)

This is an object representing a connection to MySQL Server.

2

str(Mandatory)

This is string value specifying the required query.

Return Values

This function returns a statement object incase of success and false incase of failure.

PHP Version

This function was first introduced in PHP Version 5 and works works in all the later versions.

Example

Following example demonstrates the usage of the mysqli_prepare() function (in procedural style) −

<?php
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   $query = "CREATE TABLE Test(Name VARCHAR(255), AGE INT)"; 
   mysqli_query($con, $query);
   print("Table Created.....\n");

   $stmt = mysqli_prepare($con, "INSERT INTO Test values(?, ?)");
   mysqli_stmt_bind_param($stmt, "si", $Name, $Age);
   $Name = 'Raju';
   $Age = 25;
   print("Record Inserted.....");

   //Executing the statement
   mysqli_stmt_execute($stmt);

   //Closing the statement
   mysqli_stmt_close($stmt);

   //Closing the connection
   mysqli_close($con);
?>

This will produce following result −

Table Created.....
Record Inserted.....

If you verify the contents of the table as shown below $minus;

mysql> select * from test;
+------+------+
| Name | AGE  |
+------+------+
| Raju |   25 |
+------+------+
1 row in set (0.00 sec)

Example

In object oriented style the syntax of this function is $con-> prepare(); Following is the example of this function in object oriented style $minus;

<?php
   //Creating a connection
   $con = new mysqli("localhost", "root", "password", "mydb");

   $query = "CREATE TABLE Test(Name VARCHAR(255), AGE INT)"; 
   $con -> query($query);
   print("Table Created.....\n");

   $stmt = $con -> prepare( "INSERT INTO Test values(?, ?)");
   $stmt -> bind_param("si", $Name, $Age);
   $Name = 'Raju';
   $Age = 25;
   print("Record Inserted.....");

   //Executing the statement
   $stmt->execute();

   //Closing the statement
   $stmt->close();

   //Closing the connection
   $con->close();
?>

This will produce following result −

Table Created.....
Record Inserted.....
php_function_reference.htm
Advertisements