使用新选择值重复PHP查询?

时间:2011-07-02 14:48:46

标签: php loops pdo prepared-statement

是否有更简单的方法来执行此操作,而不是将同一行代码写入100次以上?我每次都需要字段L_key的值,你会注意到:

$query1 = "SELECT L_key FROM profiles WHERE v_key = '$L1_key'";
$result = mysqli_query($dbh, $query1);
if ($row = mysqli_fetch_array($result)) 
{
    $L2_key = $row['L_Key'];
    $query2 = "UPDATE profiles SET min = min + 1 WHERE v_key = '$L2_key'";
    mysqli_query($dbh, $query2);
} 

$query3 = "SELECT L_key FROM profiles WHERE v_key = '$L2_key'";
$result = mysqli_query($dbh, $query1);
if ($row = mysqli_fetch_array($result)) 
{
    $L3_key = $row['L_Key'];
    $query2 = "UPDATE profiles SET min = min + 1 WHERE v_key = '$L3_key'";
    mysqli_query($dbh, $query2);
} 

$query3 = "SELECT L_key FROM profiles WHERE v_key = '$L3_key'";
$result = mysqli_query($dbh, $query1);
if ($row = mysqli_fetch_array($result)) 
{
    $L4_key = $row['L_Key'];
    $query2 = "UPDATE profiles SET min = min + 1 WHERE v_key = '$L4_key'";
    mysqli_query($dbh, $query2);
} 

$query3 = "SELECT L_key FROM profiles WHERE v_key = '$L4_key'";
$result = mysqli_query($dbh, $query1);
if ($row = mysqli_fetch_array($result)) 
{
    $L5_key = $row['L_Key'];
    $query2 = "UPDATE profiles SET min = min + 1 WHERE v_key = '$L5_key'";
    mysqli_query($dbh, $query2);
} 

我是否使用循环?如果是这样,你能不能给我一个代码来反复执行,因为我还在学习,不知道循环是什么?或者,有不同的方法吗?

3 个答案:

答案 0 :(得分:1)

如果我理解正确,你可以使用mysql_num_rows或mysql_result来获取总数,这样就可以使用一段时间了:

<? $a = 0; while($total != $a) { //query $a++; } ?>

答案 1 :(得分:1)

您的配置文件表(v_key => (l_key : v_key)=> ( l_key... ))中有一个递归结构,SQL并不能真正处理简单查询的错误。您可以选择编写存储过程或使用PHP处理它。从初学者开始,我认为PHP对于这项任务来说简单得多:

<?php
// define a variable on the outside -- we'll need it for each iteration
$lKey;
// If you know how many are going to be used, use a for loop because 
// then you know you won't get some sort of nasty infinite recursion issue.
// $count is however many times this needs to operate.
for($i = 0; $i < $count; $i++ )
// while( true ) // <-- this will keep going until "break" is called.
// If you don't know how many will be used. Comment out the for loop
// and uncomment thie while loop.
{
    // your initial query -- I added a limit because you only need one
    // and there is no sense in doing anything more than what you need
    $query1 = "SELECT L_key FROM profiles WHERE v_key = '$lKey' LIMIT 1";
    $result = mysqli_query($dbh, $query1);
    if ($row = mysqli_fetch_array($result)) // so far so good. 
    {
        $lKey = $row['L_Key']; // assign that outside variable to the new key
        // and run the necessary update.
        $query2 = "UPDATE profiles SET min = min + 1 WHERE v_key = '$lKey'";
        mysqli_query($dbh, $query2);
    } 
    else
    {
        break;
    }
    // as of right now, $lKey is now the value from the select above.
    // which means that you'll be able to start the next loop with it.
}

答案 2 :(得分:0)

使用pdo解决所有后顾之忧。这是使用预准备语句在pdo中的cinche。甚至会表现得更好。