MLK MLK - 1 year ago 59
PHP Question

DBAL inside of for loop doesn't work properly

I created a function inside a longer plug-in for shopware, which is supposed to create a random number for every row in the database that has a "NULL" value in the "vouchercode" column. Right now I replaced the for-loop condition with a fixed number, because I wanted to make sure the problem doesn't occur because of the for-loop condition.

The problem is, that the for-loop just has effect on the database once.

For instance: I have this table 's_plugin_tnev'. Inside of that table are 6 rows. 4 of these have "NULL" as value inside of the vouchercode column.

So as far as I understand my code. It should loop 5 times through the same table and every time update one of those "NULL"-value columns, meanwhile after every loop one of those "NULL"-value columns should be filled with a random number and therefore no longer be SELECTed nor UPDATEd by this for-loop.

Though as mentioned earlier this doesn't happen. The for loop just works once apparently.

Here is my code snippet:

public function generateCode()
{
//Repeat action 5 times
for($i = 0; $i <= 4; $i++)
{
$rand = 0;
//Creates 16 times a number and add it to the var
for ($i = 0; $i<15; $i++)
{
$rand .= mt_rand(0,9);
}
//On Checkoutcomplete add $rand to database table
$addInt = "UPDATE s_plugin_tnev SET vouchercode = $rand
WHERE vouchercode IS NULL
LIMIT 1";
$connect = Shopware()->Db()->query($addInt);
}
}


As you can see I use the DBAL Framework, because this is the best supported way by Shopware.

My idea would be that the mistake has something to do with the $connect variable or that DBAL is not communicating fast enough with the Database.

Maybe someone has more experience with DBAL and could help me out.

Thanks in advance,
Max K

Answer Source

You have two for loops with $i, so on your first iteration, at the end the $i value is 15 and the first loop is executed only once.

Try this instead :

public function generateCode()
{
  //Repeat action 5 times
  for($i = 0; $i <= 4; $i++) 
  {
    $rand   = 0;
    //Creates 16 times a number and add it to the var
    for ($j = 0; $j<15; $j++) // $j NOT $i <---
    {
        $rand .= mt_rand(0,9);
    }
    //On Checkoutcomplete add $rand to database table
    $addInt    = "UPDATE s_plugin_tnev SET vouchercode = $rand 
                  WHERE vouchercode IS NULL
                  LIMIT 1";
    $connect = Shopware()->Db()->query($addInt);
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download