I have 2 queries that I have to run:
- A complex SELECT query in a stored procedure to identify which records I need to modify.
- An UPDATE using the record id's from the first that modifies values in the same table.
I try to get the results from the first to close so I can run the second, but the only way I can do so without getting this error :
Commands out of sync; you can't run this command now
is to close the mysqli connection and re-create it.
Here's the essence of my code:
// The $sql is to run a stored procedure. I omitted that code
// because it's very lengthy, but it works perfectly every time.
// The stored procedure is basically a recursive SELECT query to
// pull hierarchical data from a self-referencing data set.
$res = mysqli_query($mysqli, $sql);
// Build a comma-delimited list of id numbers
$ids = "";
$i = 0;
$qty = mysqli_num_rows($res);
while ($recs = mysqli_fetch_array($res)) {
$i += 1;
$ids .= $recs["data_id"];
if ($i < $qty) $ids .= ", ";
}
mysqli_free_result($res);
// Close connection to MySQL (Remove this & connect statement below causes it to fail)
mysqli_close($mysqli);
// Re-open connection to MySQL (Remove this & close statement above causes it to fail)
$mysqli = connect_DB();
$sql = "UPDATE data SET data_val = data_val + ".$val." WHERE data_id IN (".$ids.")";
$res = mysqli_query($mysqli, $sql);
I've tried every suggestion I found (including more than a dozen from stackoverflow posts), but nothing works. What am I missing? It sure seems unreasonable to have to do that, especially considering that I can run other queries back-to-back by using a "free_result" statement.