如何检查表中是否已存在引脚并重定向

时间:2015-10-19 15:13:41

标签: php mysql

我想检查表中是否已存在引脚。如果存在,它应该回显消息并重定向到另一个页面。

$result = mysql_query("SELECT * FROM pin WHERE Pin  = '$Pin'");
$test = mysql_fetch_array($result);

$test = array();
while ($row = mysql_fetch_array($result)) {
$test[] = array_map('utf8_encode', $row);
}

if($test["number_update"] == 1) { 
echo 'Pin Already in Use, Please Login';
header("location:compet_start.php");
} else {

mysql_query("UPDATE pin SET appid ='$num', number_update='1' WHERE Pin= '$Pin'")
        or die(mysql_error()); 

mysql_query("INSERT IGNORE INTO pinlog (TableName,pin,id,TIME_UPDATED) VALUES('Pin','$Pin','$num','$date')")
        or die(mysql_error()); 

header("location:compet_applicant.php?pin=$Pin");
}
}
}
?>  

3 个答案:

答案 0 :(得分:0)

请尝试以下代码:

$result = mysql_query("SELECT * FROM pin WHERE Pin  = '$Pin'");
$num = mysql_num_rows($result);
if ($num > 0) {
 echo "Pin exists";
}
else {
  echo "Pin does not exist";
}

答案 1 :(得分:0)

如果您确定只有1条记录WHERE Pin = '$Pin',那么您可以:

$result = mysql_query("SELECT * FROM pin WHERE Pin  = '$Pin'");
if($test = mysql_fetch_array($result) && $test["number_update"] == 1) { 
echo 'Pin Already in Use, Please Login';
header("location:compet_start.php");
} else {
...

在你的问题中你写了我想检查表中是否已存在引脚所以如果你只是需要检查它是否存在,你可以删除&& $test["number_update"] == 1并简化条件:

if($test = mysql_fetch_array($result)) { 

评论 echo之前没有理由header("location,因为用户永远不会看到echo文字

//echo 'Pin Already in Use, Please Login'; <-- this should be deleted
header("location:compet_start.php");

答案 2 :(得分:0)

如果您只对某行存在感兴趣,您还可以查看mySQL的EXISTS子查询。 它会返回true或false并且更清晰,它也会比获取所有答案更快。

 "SELECT EXISTS(SELECT * FROM pin WHERE Pin  = '$Pin')"

见这里: https://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html