0

When I was using multi_query with SELECT, it looked like this:

$sql = 'SELECT....';
$sql .= 'SELECT....';
...

if ($db->multi_query($sql))
{ 
    do
    {
        if ($stmt = $db->store_result())
        {
            while ($row = $stmt->fetch_assoc())
            {
                foreach ($row as $key => $value)
                {
                    $var[$key] = $value;
                }
            }
            $stmt->free_result();
        }
    } while ($db->more_results() && $db->next_result());
}

But how should it look when I need DELETE or UPDATE only, since there are no results?

$sql = 'DELETE...';
$sql .= 'DELETE...';
$sql .= 'UPDATE...';

if ($db->multi_query($sql))
{
    do
    {
        /*well.. nothing?*/
    }
    while ($db->more_results() && $db->next_result());
}

seems to work, even without the do {...}, but isn't there a better / clean solution?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
qlt
  • 55
  • 1
  • 3
  • 10

1 Answers1

1

As far as I remember you are on the right way of executing multiple updates. The one thing you seem to miss is checking for errors . For instance (from here),

if ($db->multi_query($sql))
{
  do
  {
  // do nothing, just iterate over results to make sure no errors  
  }
  while ($db->next_result());
}
if ($db->errno) {
    //error handling
}
a1ex07
  • 36,826
  • 12
  • 90
  • 103
  • You're right, I should check for errors.. that's also on my list of improvements :) But first of all I was trying to remove unnecessary code, improve queries etc., so I came to the question if an empty `do {...} while` loop is the right way here – qlt Aug 28 '12 at 17:02
  • I think so. Otherwise, you cannot check if all queries in the batch completed without errors ("Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first." - multi_query documentation) – a1ex07 Aug 28 '12 at 17:09
  • That's true.. but is the `do { ... }` part necessary here? `while ($db->more_results() && $db->next_result());` only seems to work too, but looks a bit strange.. same for `while ($db->more_results()) { $db->next_result(); }` .. or did I miss something? – qlt Aug 28 '12 at 17:36