对SQL查询进行while循环


Making a while loop out of SQL queries

我一直在尝试设置一种方法,将下面的代码段2转换为while循环。按照目前的情况,代码段2必须复制并粘贴4次才能获得正确的效果。如何递增变量所指向的SQL查询?

我的问题是试图使这个部分能够循环工作。所以它第一次使用查询9,然后是查询10,然后是11,依此类推。所以在//WHILE LOOP HERE所在的地方,会有一个循环,它会运行整个过程5次,但会更改要更新的内容。

            // Update the Mob Position
        $statement9 = $db->prepare($query9);
        $result9 = $statement9 -> execute(array(
        'mob_list_id' =>$id,
        'mob_1_x' =>$mob_number_y[0],
        'mob_1_y' =>$mob_number_y[0] - 32
        ));

代码段1

$query9 = "UPDATE mob_1
       SET mob_1_x = :mob_1_x, mob_1_y =:mob_1_y
       WHERE mob_list_id = :mob_list_id";
$query10 = "UPDATE mob_1
       SET mob_2_x = :mob_2_x, mob_2_y =:mob_2_y
       WHERE mob_list_id = :mob_list_id";
$query11 = "UPDATE mob_1
       SET mob_3_x = :mob_3_x, mob_3_y =:mob_3_y
       WHERE mob_list_id = :mob_list_id";
$query12 = "UPDATE mob_1
       SET mob_4_x = :mob_4_x, mob_4_y =:mob_4_y
       WHERE mob_list_id = :mob_list_id";
$query13 = "UPDATE mob_1
       SET mob_5_x = :mob_5_x, mob_5_y =:mob_5_y
       WHERE mob_list_id = :mob_list_id";

代码段2

$roll = 0;
// WHILE LOOP HERE
{
$roll = mt_rand(1,6);
if ( $roll == 1 || $roll == 5 )
{
$direction = mt_rand(1,4);
if ( $direction == 1 )
{
    if ( $mob_number_y[0] > 126 )
    {
        // Update the Mob Position
        $statement9 = $db->prepare($query9);
        $result9 = $statement9 -> execute(array(
        'mob_list_id' =>$id,
        'mob_1_x' =>$mob_number_x[0],
        'mob_1_y' =>$mob_number_y[0] - 32
        ));
        $mob_number_y[0]-= 32;
    }
}
if ( $direction == 2 )
{
    if ( $mob_number_x[0] > 240 )
    {
    // Update the Mob Position
    $statement9 = $db->prepare($query9);
    $result9 = $statement9 -> execute(array(
    'mob_list_id' =>$id,
    'mob_1_x' =>$mob_number_x[0] - 32,
    'mob_1_y' =>$mob_number_y[0]
    ));
    $mob_number_x[0]-= 32;
    }
}
if ( $direction == 3 )
{
    if ( $mob_number_x[0] < 848 )
    {
        // Update the Mob Position
        $statement9 = $db->prepare($query9);
        $result9 = $statement9 -> execute(array(
        'mob_list_id' =>$id,
        'mob_1_x' =>$mob_number_x[0] + 32,
        'mob_1_y' =>$mob_number_y[0]
        ));
        $mob_number_x[0]+= 32;
    }
}
if ( $direction == 4 )
{
    if ( $mob_number_y[0] < 734 )
    {
        // Update the Mob Position
        $statement9 = $db->prepare($query9);
        $result9 = $statement9 -> execute(array(
        'mob_list_id' =>$id,
        'mob_1_x' =>$mob_number_x[0],
        'mob_1_y' =>$mob_number_y[0] + 32
        ));
        $mob_number_y[0]+= 32;
    }
}
}
}

使用

$direction = mt_rand(9,13);

然后将变量生成为动态或可变变量(http://docs.php.net/manual/en/language.variables.variable.php)像这样

$statement{$direction} = $db->prepare($query{$direction});

etc-或者你可以让你的查询和其他变量数组

$query[9] = "UPDATE mob_1
   SET mob_1_x = :mob_1_x, mob_1_y =:mob_1_y
   WHERE mob_list_id = :mob_list_id";

只需使用

$direction = mt_rand(9,13);
$statement[$direction] = $db->prepare($query[$direction]);