PHP mysqli_stmt execute() Method
The PHP mysqli_stmt::execute() / mysqli_stmt_execute() function executes a prepared statement. The statement must be successfully prepared prior to execution, using either the mysqli_prepare() or mysqli_stmt_prepare() function, or by passing the second argument to mysqli_stmt::__construct().
If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function. If the query yields a result set, it can be fetched using mysqli_stmt_get_result() function or by fetching it row by row directly from the statement using mysqli_stmt_fetch() function.
Syntax
//Object-oriented style public mysqli_stmt::execute(params) //Procedural style mysqli_stmt_execute(statement, params)
Parameters
statement |
Required. For procedural style only: Specify a mysqli_stmt object returned by mysqli_stmt_init(). |
params |
Optional. Specify a list array with as many elements as there are bound parameters in the SQL statement being executed. Each value is treated as a string. |
Return Value
Returns true on success or false on failure.
Example: Object-oriented style
The example below shows the usage of mysqli_stmt::execute() 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_execute() 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