通过PHP中的MySQL查询循环

时间:2015-05-20 20:17:45

标签: php mysql sql

我有一些查询MySQL数据库的代码。我的问题是,如果只检查我表的第一行。我知道我需要一个for循环,但我尝试的东西不起作用。仅检查第一行的工作代码是

public function checkPart($aid, $uname) {
    $result = mysql_query("SELECT * FROM part WHERE aid = '$aid'") or die(mysql_error());
    // check for result 
    $no_of_rows = mysql_num_rows($result);

        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            $aiddb = $result['aid'];
            $unamedb = $result['uname'];

            if ($unamedb == $uname) {
                // user authentication details are correct
                return $result;
            }
        } else {
            // user not found
            return mysql_error();
        }

}

我试过的是:

public function checkPart($aid, $uname) {
    $result = mysql_query("SELECT * FROM part WHERE aid = '$aid'") or die(mysql_error());
    // check for result 
    $no_of_rows = mysql_num_rows($result);
    for($x=1; $x<= $no_of_rows;$x++){
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            $aiddb = $result['aid'];
            $unamedb = $result['uname'];

            if ($unamedb == $uname) {
                // user authentication details are correct
                return $result;
            }
        } else {
            // user not found
            return mysql_error();
        }
    }
}

有人可以帮我纠正我的代码吗?如果问题太简单,我是初学者,请原谅我。

2 个答案:

答案 0 :(得分:1)

实现此目的的事实上的方法是使用while循环:

$no_of_rows = mysql_num_rows($result);
if ($no_of_rows == 0) {
    return mysql_error();
} else {
    while ($row = mysql_fetch_assoc($result)) {
        // ... use $row['aid'], $row['uname'], etc.
    }
}

您自己的代码可能有效,但您覆盖了$result

$result = mysql_fetch_array($result);

因此,在循环的一次迭代之后,您丢失了查询的结果。

注意:mysql_*函数are deprecated由于安全问题,建议您先学习mysqli_*PDO

答案 1 :(得分:1)

public function checkPart($aid, $uname) 
{
        // It's think it's better to distinct the query itself
        // Therefore u can re-use the code easily.

       $sql = "SELECT * FROM part WHERE aid = \"$aid\"";
       $result = mysql_query($sql);

       // Catch errors
       if (!$result) 
       {
           die('Invalid query: ' . mysql_error());
       }

       // If i'm correct u're using for just to loop the result
       // of fetch_array
      // It's easier like in the example in the man to do

       while ($row = mysql_fetch_array($result))
       {
           // Didn't see where this variable is used but u'll use later i suppose

           $aiddb = $row['aid'];
           $unamedb = $row['uname'];

           if ($unamedb == $uname) 
           {
               // user authentication details are correct
               return $result;
           }
           else
              echo 'User not found \n';
    }
} // checkPart()

我对编码很新,但我建议你多读这个人。这真的帮助了我。顺便说一句,你应该看一下PDO的数据库查询。

来源:

PHP.net fetch_array

PDO introduction