I'm trying to bind parameters (for security) and then get the result into an array, so I created code like the following. The problem is that it doesn't work: $arr
is null. (BTW I know the query in getList
works.)
if ($stmt = mysqli_prepare($con, "call getList(?)")) {
mysqli_stmt_bind_param($stmt, 's', $userInputSearch);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$arr = mysqli_fetch_all($result, MYSQLI_ASSOC);
$jsonArr = json_encode($arr);
echo $jsonArr;
Note that I've got mysqli_fetch_all
to work when using mysqli_query()
.
On mysqli_fetch_all reference, I found this comment:
Also, mysqli_fetch_all works only for buffered result sets, which are the default for mysqli_query. MYSQLI_USE_RESULT will be supported in 5.3.4+ However, it makes little sense to use it this way, materialising unbuffered sets. In this case choose STORE_RESULT, and fetch_all won't copy the data, but reference it, as it is stored already in mysqlnd.
I discovered that prepared statements return unbuffered results, so I tried using $result = mysqli_stmt_store_result($stmt)
instead of $result = mysqli_stmt_get_result($stmt);
However that didn't help.
That leaves me not completely at a loss — I understand that I could loop to load the data one row at a time, but I really don't want to have to loop in PHP just to do something as simple as get an array from a prepared statement. Is there a way to acquire and deal with the result set as one object?
I've just reread documentation...
I have no possibility to test mysql right now.
But just a guess:
mysqli_fetch_all ( mysqli_result $result ...
Parameters result Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().
I want to highlight that all functions mysqli_query(), mysqli_store_result() mysqli_use_result()
belongs to mysqli class, not to stmt
and they return type mysqli_result
but you are trying to use mysqli_stmt_get_result($stmt);
mysqli_result mysqli_stmt_get_result ( mysqli_stmt $stmt )
...Return Values
Returns a resultset or FALSE on failure.
So this function return type resultset
not mysqli_result
.
So you have to change your code to use no mysqli_stmt
so change :
if ($stmt = mysqli_prepare($con, "call getList(?)")) {
mysqli_stmt_bind_param($stmt, 's', $userInputSearch);
mysqli_stmt_execute($stmt);
to
$result = mysqli_query ( $con , "call getList(".mysqli_real_escape_string($userInputSearch).")" );
, or just change your line:
$arr = mysqli_fetch_all($result, MYSQLI_ASSOC);
to
$arr = array()
while ($row = $result->fetch_array())
{
arr[] = $row ;
}
Sorry if any error, have no possibility to trace and debug right now, hope it is helpful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.