2 prepared statements, 2 stored procedures, 1 mysqli connection

隐身守侯 提交于 2019-12-05 03:24:03

Well, I'll try to answer for the question title, assuming that in the first statement not a regular query but one of two aforementioned stored procedures were called.

After calling a stored procedure, you always have to move over additional empty result set returned by every stored procedure:

$mysqli->next_result();

Also, after first prepared function call, add one extra fetch() after getting your data:

$stmt->fetch();
$stmt->free_result();

as you have to "free" the result set waiting on the server side. It could be done in many ways, but simplest would be just calling fetch() one more time, or, more strictly put, you have to call fetch() until it returns FALSE, indicating that there are no more rows left in the resultset. You are doing it [silently] in the other snippets, when calling fetch() in the while loop, but here, fetching only one row, you have to call it explicitly.

There is another way, way more convenient: use get_result() (if available) which will solve all your problems at once. Instead of that long and windy code you have at the moment, only four lines actually needed:

$stmt = $mysqli->prepare('CALL getWeeksSummary(?,?,?)');
$stmt->bind_param('sss', $a, $b, $c);
$stmt->execute();
$weeksSummary = $stmt->get_result()->fetch_object();

get_result() will free that waiting resultset and at the same time allow you to use fetch_object() method, which will let you to get the resulting object in just one line.

Reading the mysqli documentation, it says that $stmt->free_result() is to free the memory allocated from $stmt->store_result(). Since the code doesn't use store_result(), removing free_result() solves the errors.

Of course, it also says to use store_result() whenever a query returns a result set. I don't really understand why (something to do with buffering), but since these two prepared statements and stored procedures work without store_result(), the problem is solved.

I'm still curious why it doesn't work with store_result() and free_result(), but at least there is some working code now. Here is the modified code at tutorialspoint.


As a side note, instead of using two prepared statements with two stored procedures, a way around it is to use one prepared statement to set variables

$stmt = $mysqli->prepare('SET @a = ?, @b = ?, @c = ?')
...

then use those variables in queries to call the stored procedures

$result = $mysqli->query('CALL getWeeks(@a,@b,@c)')
...
$result = $mysqli->query('CALL getWeeksSummary(@a,@b,@c)')
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!