- PHP get_result() and mysqli_stmt_get_result()
- PHP get_result()
- PHP get_result() Syntax
- PHP mysqli_stmt_get_result()
- PHP mysqli_stmt_get_result() Syntax
- mysqli_stmt_get_result
- Возвращаемые значения
- Только для MySQL Native Driver
- Примеры
- Смотрите также
- PHP mysqli_stmt_get_result() Function
- Syntax
- Parameters
- Return Values
- PHP Version
- Example
- Example
PHP get_result() and mysqli_stmt_get_result()
This article is created to cover the two functions of PHP, namely:
Both functions are used to get a result set from a prepared statement as a mysqli_result object. The only difference is that get_result() uses PHP mysqli object-oriented script, whereas mysqli_stmt_get_result() uses PHP mysqli procedural script.
PHP get_result()
The PHP get_result() function returns a result set from a prepared statement as a mysqli_result object in object-oriented style. For example:
connect_errno) < echo "Database connection failed!"; echo "Reason: ", $conn->connect_error; > else < $sql = "SELECT name, age FROM customer"; $stmt = $conn->prepare($sql); if($stmt->execute() == true) < $result = $stmt->get_result(); while($row = $result->fetch_array()) < echo "Name: ", $row[0]; echo ""; echo "Age: ", $row[1]; echo ""; > > > $conn->close(); ?>
The output of the above PHP example using the get_result() function is shown in the snapshot given below:
Note: The mysqli() function is used to open a connection to the MySQL database server in object-oriented style.
Note: The new keyword is used to create a new object.
Note: The connect_errno is used to get or return the error code (if any) from the last connect call in object-oriented style.
Note: The connect_error is used to get the error description (if any) from the last connection in object-oriented style.
Note: The prepare() function is used to prepare an SQL statement before its execution on the MySQL database in object-oriented style, to avoid SQL injection.
Note: The execute() function is used to execute a prepared statement on the MySQL database in object-oriented style.
Note: The fetch_array() function is used when we need to fetch and get the result as an enumerated array, an associative array, or both in object-oriented style.
Note: The close() function is used to close an opened connection in object-oriented style.
The above example can also be written as:
connect_errno) < $stmt = $conn->prepare("SELECT name, age FROM customer"); $stmt->execute(); $result = $stmt->get_result(); while($row = $result->fetch_array()) < echo "Name: ", $row[0]; echo ""; echo "Age: ", $row[1]; echo ""; > > $conn->close(); ?>
PHP get_result() Syntax
The syntax of the get_result() function in PHP is:
PHP mysqli_stmt_get_result()
The PHP mysqli_stmt_get_result() function returns a result set from a prepared statement as a mysqli_result object in procedural style. For example:
"; echo "Age: ", $row[1]; echo ""; > > mysqli_close($conn); ?>
Note: The mysqli_connect() function is used to open a connection to the MySQL database server in procedural style.
Note: The mysqli_connect_errno() function is used to get or return the error code (if any) from the last connect call in procedural style.
Note: The mysqli_prepare() function is used to prepare an SQL statement before its execution on the MySQL database in procedural style, to avoid SQL injection.
Note: The mysqli_stmt_execute() function is used to execute a prepared statement on the MySQL database in procedural style.
Note: The mysqli_fetch_array() function is used when we need to fetch and get the result as an enumerated array, an associative array, or both in procedural style.
Note: The mysqli_close() function is used to close an opened connection to the MySQL database in procedural style.
PHP mysqli_stmt_get_result() Syntax
The syntax of the mysqli_stmt_get_result() function in PHP is:
mysqli_stmt_get_result($mysqli_stmt)
mysqli_stmt_get_result
Только для процедурного стиля: Идентификатор выражения, полученный с помощью mysqli_stmt_init() .
Возвращаемые значения
Возвращает результат или FALSE в случае возникновения ошибки.
Только для MySQL Native Driver
Доступно только с расширением mysqlnd.
Примеры
Пример #1 Объектно-ориентированный стиль
$mysqli = new mysqli ( «127.0.0.1» , «user» , «password» , «world» );
if( $mysqli -> connect_error )
die( » $mysqli -> connect_errno : $mysqli -> connect_error » );
>
$query = «SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1» ;
$stmt = $mysqli -> stmt_init ();
if(! $stmt -> prepare ( $query ))
print «Ошибка подготовки запроса\n» ;
>
else
$stmt -> bind_param ( «s» , $continent );
$continent_array = array( ‘Europe’ , ‘Africa’ , ‘Asia’ , ‘North America’ );
foreach( $continent_array as $continent )
$stmt -> execute ();
$result = $stmt -> get_result ();
while ( $row = $result -> fetch_array ( MYSQLI_NUM ))
foreach ( $row as $r )
print » $r » ;
>
print «\n» ;
>
>
>
$stmt -> close ();
$mysqli -> close ();
?>
Пример #2 Процедурный стиль
$link = mysqli_connect ( «127.0.0.1» , «user» , «password» , «world» );
if (! $link )
$error = mysqli_connect_error ();
$errno = mysqli_connect_errno ();
print » $errno : $error \n» ;
exit();
>
$query = «SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1» ;
$stmt = mysqli_stmt_init ( $link );
if(! mysqli_stmt_prepare ( $stmt , $query ))
print «Ошибка подготовки запроса\n» ;
>
else
mysqli_stmt_bind_param ( $stmt , «s» , $continent );
$continent_array = array( ‘Europe’ , ‘Africa’ , ‘Asia’ , ‘North America’ );
foreach( $continent_array as $continent )
mysqli_stmt_execute ( $stmt );
$result = mysqli_stmt_get_result ( $stmt );
while ( $row = mysqli_fetch_array ( $result , MYSQLI_NUM ))
foreach ( $row as $r )
print » $r » ;
>
print «\n» ;
>
>
>
mysqli_stmt_close ( $stmt );
mysqli_close ( $link );
?>
Результат выполнения данных примеров:
Albania 3401200 Europe Algeria 31471000 Africa Afghanistan 22720000 Asia Anguilla 8000 North America
Смотрите также
- mysqli_prepare() — Подготавливает SQL выражение к выполнению
- mysqli_stmt_result_metadata() — Возвращает метаданные результирующей таблицы подготавливаемого запроса
- mysqli_stmt_fetch() — Связывает результаты подготовленного выражения с переменными
- mysqli_fetch_array() — Выбирает одну строку из результирующего набора и помещает ее в ассоциативный массив, обычный массив или в оба
- mysqli_stmt_store_result() — Передает результирующий набор запроса на клиента
PHP mysqli_stmt_get_result() Function
The mysqli_stmt_get_result() function accepts a statement object as a parameter, retrieves the result set from the given statement (if there are any) and returns it.
You cannot close persistent connections using this function.
Syntax
mysqli_stmt_get_result($stmt);
Parameters
This is an object representing a prepared statement.
Return Values
The PHP mysqli_stmt_get_result() function returns a resultset if the statement executed is SELECT and if it is successful. In other scenarios this function returns FALSE.
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_stmt_get_result() function (in procedural style) −
print("\n"); > //Closing the statement mysqli_stmt_close($stmt); //Closing the connection mysqli_close($con); ?>
This will produce following result −
Table Created. Record Inserted. 1 Sikhar Dhawan Delhi India 2 Jonathan Trott CapeTown SouthAfrica
Example
In object oriented style the syntax of this function is $stmt->get_result(); Following is the example of this function in object oriented style $minus;
query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)"); $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("Table Created. \n"); $stmt = $con -> prepare( "SELECT * FROM Test WHERE Name in(?, ?)"); $stmt -> bind_param("ss", $name1, $name2); $name1 = 'Raju'; $name2 = 'Rahman'; print("Records Inserted. \n"); //Executing the statement $stmt->execute(); //Getting the result $res = $stmt->get_result(); print_r($res); //Closing the statement $stmt->close(); //Closing the connection $con->close(); ?>
This will produce following result −
Table Created. Records Inserted. mysqli_result Object ( [current_field] => 0 [field_count] => 2 [lengths] => [num_rows] => 6 [type] => 0 )