PHP mysqli stmt_init() Function
Example - Object Oriented style
Initialize a statement and return an object to use with stmt_prepare():
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$city="Sandnes";
// Create a prepared statement
$stmt = $mysqli -> stmt_init();
if ($stmt
-> prepare("SELECT District FROM City WHERE Name=?")) {
// Bind parameters
$stmt -> bind_param("s", $city);
// Execute query
$stmt -> execute();
// Bind result variables
$stmt -> bind_result($district);
// Fetch value
$stmt -> fetch();
printf("%s is in district %s", $city, $district);
// Close statement
$stmt -> close();
}
$mysqli -> close();
?>
Look at example of procedural style at the bottom.
Definition and Usage
The stmt_init() / mysqli_stmt_init() function initializes a statement and returns an object suitable for mysqli_stmt_prepare().
Syntax
Object oriented style:
$mysqli -> stmt_init()
Procedural style:
mysqli_stmt_init(connection)
Parameter Values
Parameter | Description |
---|---|
connection | Required. Specifies the MySQL connection to use |
Technical Details
Return Value: | Returns an object |
---|---|
PHP Version: | 5+ |
Example - Procedural style
Initialize a statement and return an object to use with mysqli_stmt_prepare():
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$city="Sandnes";
// Create a prepared statement
$stmt = mysqli_stmt_init($con);
if (mysqli_stmt_prepare($stmt, "SELECT District FROM City WHERE Name=?")) {
// Bind parameters
mysqli_stmt_bind_param($stmt, "s", $city);
// Execute query
mysqli_stmt_execute($stmt);
// Bind result variables
mysqli_stmt_bind_result($stmt, $district);
// Fetch value
mysqli_stmt_fetch($stmt);
printf("%s is in district %s", $city, $district);
// Close statement
mysqli_stmt_close($stmt);
}
mysqli_close($con);
?>
❮ PHP MySQLi Reference