由于循环导致重复的结果

时间:2014-03-06 17:11:50

标签: php

因此,我的代码从上一页获取值,将其与数据库中的表字段进行比较,并显示成功或失败。这是原始代码:

<?php
if ($_GET['q'] !='')
{
    include('config.inc');
    $foo = $_GET['q'];
    $query= "INSERT INTO register(name) VALUES('$foo')";

    $result = mysql_query("SELECT * FROM user_student");
    while($row = mysql_fetch_array($result))
    {
        $id= $row['sid'];
        if($id==$foo)
        {
            $res = mysql_query($query);
            if ($res)
            {
                echo 'Insertion ok';
            }
            else
            {
                echo " ";
                echo "Attendance already taken for $foo";
            }
        }
        else
        {
            echo " ";
            echo "Student $foo does not exist!!";
        }
    }

}
else echo "Invalid Command";
?>

有重复的结果,例如学生1124不存在!! 10次。我将代码修改为:

while($row = mysql_fetch_array($result))
{
    $id= $row['sid'];
    if($id==$foo)
    {
        $res = mysql_query($query);
    }
    else
    {
        echo " ";
        echo "Student $foo does not exist!!";
    }
}
if ($res)
{
    echo 'Insertion ok';
}
else
{
    echo " ";
    echo "Attendance already taken for $foo";
}

所以我将$ res置于循环之外以避免重复结果,但现在它说:变量无法解决有任何建议吗?

2 个答案:

答案 0 :(得分:2)

CaldasGSM的一些改变版本:

<?php
if (!empty($_GET['q']))
{
    include('config.inc');
    $foo = mysql_real_escape_string($_GET['q']);

    $result = mysql_query("SELECT * FROM user_student WHERE sid = '{$foo}'");
    $num_rows = mysql_num_rows($result);
    if($num_rows > 0)
    {
        $res = mysql_query("INSERT INTO register(name) VALUES('$foo')");
        if ($res)
        {
            echo 'Insertion ok';
        }
        else
        {
            echo " ";
            echo "Attendance already taken for $foo";
        }
    }
    else
    {
        echo " ";
        echo "Student $foo does not exist!!";
    }
}
else
{
 echo "Invalid Command";
}
?>

答案 1 :(得分:0)

可能像

<?php
if ($_GET['q'] !='')
{
    include('config.inc');
    $foo = $_GET['q'];

    $result = mysql_query("SELECT * FROM user_student");
    $bRecordExists = false;
    while($row = mysql_fetch_array($result))
    {
        $id= $row['sid'];
        if($id==$foo)
        {
            $bRecordExists = true;
            break;
        }
    }
    if($bRecordExists)
    {
            $res = mysql_query("INSERT INTO register(name) VALUES('$foo')");
            if ($res)
            {
                echo 'Insertion ok';
            }
            else
            {
                    echo " ";
                    echo "Attendance already taken for $foo";
            }
    }
    else
    {
        echo " ";
        echo "Student $foo does not exist!!";
    }

}
else
{
    echo "Invalid Command";
}
?>