PHP mysqli_stmt bind_result() Method
The PHP mysqli_stmt::bind_result() / mysqli_stmt_bind_result() function is used to bind columns in the result set to variables.
When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var/vars.
A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch() is called.
Note: All columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch().
Syntax
//Object-oriented style public mysqli_stmt::bind_param(var, vars) //Procedural style mysqli_stmt_bind_param(statement, var, vars)
Parameters
statement |
Required. For procedural style only: Specify a mysqli_stmt object returned by mysqli_stmt_init(). |
var, vars |
Required. Specify the first variable and further variables to be bound. |
Return Value
Returns true on success or false on failure.
Example: Object-oriented style
The example below shows the usage of mysqli_stmt::bind_result() method.
<?php //establishing connection to the database $mysqli = new mysqli("localhost", "user", "password", "database"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: ". $mysqli->connect_error; exit(); } //creating a prepared statement $stmt = $mysqli->stmt_init(); $query = "SELECT EmpID, Name, Age FROM Employee ORDER BY Age"; $stmt->prepare($query); //executing the SQL statement $stmt->execute(); //binding variables to prepared statement $stmt->bind_result($col1, $col2, $col3); //fetching values while ($stmt->fetch()) { printf("%s, %d\n", $col2, $col3); } //closing the connection $mysqli->close(); ?>
The output of the above code will be similar to:
Marry, 23, Kim, 26 John, 27 Adam, 28
Example: Procedural style
The example below shows the usage of mysqli_stmt_bind_result() function.
<?php //establishing connection to the database $mysqli = mysqli_connect("localhost", "user", "password", "database"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: ". mysqli_connect_error(); exit(); } //creating a prepared statement $stmt = mysqli_stmt_init($mysqli); $query = "SELECT EmpID, Name, Age FROM Employee ORDER BY Age"; mysqli_stmt_prepare($stmt, $query); //executing the SQL statement mysqli_stmt_execute($stmt); //binding variables to prepared statement mysqli_stmt_bind_result($stmt, $col1, $col2, $col3); //fetching values while (mysqli_stmt_fetch($stmt)) { printf("%s, %d\n", $col2, $col3); } //closing the connection mysqli_close($mysqli); ?>
The output of the above code will be similar to:
Marry, 23, Kim, 26 John, 27 Adam, 28
❮ PHP MySQLi Reference