mysqli_stmt fetch() Method
The mysqli_stmt::fetch() / mysqli_stmt_fetch() function is used to fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().
Note: All columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch().
Note: Data are transferred unbuffered without calling mysqli_stmt_store_result() which can decrease performance but reduces the memory cost.
Syntax
//Object-oriented style public mysqli_stmt::fetch() //Procedural style mysqli_stmt_fetch(statement)
Parameters
statement |
Required. For procedural style only: Specify a mysqli_stmt object returned by mysqli_stmt_init(). |
Return Value
Returns the following:
- true - Success. Data has been fetched.
- false - Error occurred.
- null - No more rows/data exists or data truncation occurred.
Example: Object-oriented style
The example below shows the usage of mysqli_stmt::fetch() 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_fetch() 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
❮ MySQLi Functions Reference