PHP MySQL检查ID是否存在

时间:2014-03-16 18:43:36

标签: php mysql

我做了类似的事情,但它没有用。

我想检查数据库中的ID是否存在,如果是,请插入数据,如果不再试一次。

我使用此代码进行检查,但似乎无法正常工作。

我输入的是正确的或不正确的,它会转到accepted.html页面,并且它不会在我的时间表中插入数据。我希望它检查ID是否为真在时间表中插入数据。

 if ($player == null || $witness == null) {
        echo "Do not use the same player and witness or maybe you forgot to add it...";
        echo '<META HTTP-EQUIV="Refresh" Content="2; URL=index.php">';
    } else {
        $sql = "SELECT (`id`) FROM player WHERE id={$player} ";
        $result = mysql_query($sql);
        if ($result == true) {
            $sql2 = "INSERT INTO `members` (`player`, `hours`, `minutes`, `witness`, `type`,`date`,`comments`) VALUES ('$player', '$hours', '$minutes', '$witness', '$type', '$date','$comments')";
            $result2 = mysql_query($sql2);

            if ($result2)
            {
                header('Location: accepted.html');
            }
            else {
                echo mysql_error();
            }
        }else{
            header('Location: contactAdmin.html');
        }
    }

3 个答案:

答案 0 :(得分:2)

$sql = "SELECT (`id`) FROM $tbl_name WHERE id=$$player ";

应该是

$sql = "SELECT `id` FROM $tbl_name WHERE id= $player ";

你有id=$$player

答案 1 :(得分:0)

您的代码中存在一些问题 有一件事是第一个sql查询使用了错误的变量$$player应该是$player

$sql = "SELECT `id` FROM $tbl_name WHERE id= $player ";

其次,您的插入查询永远不会执行,因为您传入了错误的变量。您传递了$sql而不是$sql2

$sql2 = "INSERT INTO `members` (`player`, `hours`, `minutes`, `witness`, `type`,`date`,`comments`) VALUES ('$player', '$hours', '$minutes', '$witness', '$type', '$date','$comments')";
$result2 = mysql_query($sql2);

第三,您的header位置错误。它应该在开幕{之后放置:

if ($result2) {
    header('Location: accepted.html');
} else {
    echo mysql_error();
}

答案 2 :(得分:0)

我发现3个错误... $ sql查询中的1个,2个,标头加载,3个,放置标头vs mysql_error。

  if ($player == null || $witness == null) {
            echo "Do not use the same player and witness or maybe you forgot to add it...";
            echo '<META HTTP-EQUIV="Refresh" Content="2; URL=index.php">';
        } else {
            $sql = "SELECT (`id`) FROM $tbl_name WHERE id='{$player}' ";
            $result = mysql_query($sql);
            if (mysql_num_rows($result) <= 0) {
                $sql2 = "INSERT INTO `members` (`player`, `hours`, `minutes`, `witness`, `type`,`date`,`comments`) VALUES ('$player', '$hours', '$minutes', '$witness', '$type', '$date','$comments')";
                $result2 = mysql_query($sql2);

                if ($result2)
                {
                     header('Location: accepted.html');
                }
                else {
                    echo mysql_error();
                }
            }else{
                header('Location: contactAdmin.html');
            }
        }

---编辑 第四:$ result2应该使用$ sql2作为查询。