我要做的是在数据库中保存一些数据,当用户按“保存”按钮时,脚本会将用户输入的数据与数据库中已存在的数据进行比较。如果数据匹配,它将显示一条警告“输入的数据已经在数据库中,请使用搜索栏进行搜索”。在我的情况下,我只想检查电话号码和cnic(cnic =国民身份证号码)。这就是我在做的事情。
<?php include_once("config.php"); // mysql_connect and database selection are in this file.
$name = $_POST['name']; // data coming from save_info.php
$gender = $_POST['option']; // data coming from save_info.php
$cnic = $_POST['cnic']; // data coming from save_info.php
$number = $_POST['number']; // data coming from save_info.php
$address = $_POST['address']; // data coming from save_info.php
$info = $_POST['info']; // data coming from save_info.php
$check = "SELECT * FROM info WHERE num = $number AND cnic = $cnic"; // checking data
$cresult = mysql_query($check);
if (mysql_num_rows($cresult)==1) {
echo "The entered phone number/cnic is already in the database, Please use search bar to search it.";
header('refresh:10;url=save_info.php');
}
else
{
$sql = "INSERT INTO info(name, gender, cnic, num, address, info)VALUES('$name', '$gender', '$cnic', '$number', '$address', '$info')";
$result = mysql_query($sql);
mysql_close();
header('Location:saved_info.php');
}
?>
答案 0 :(得分:0)
尝试在参数周围添加单引号,并像这样重写查询..
$check = "SELECT * FROM `info` WHERE `num` = '$number' OR cnic='$cnic'";
此外,在您的 if
声明中..请按此检查
if (mysql_num_rows($cresult)>0) {
此外,请停止使用 mysql_*
功能,因为它们已被弃用。改为使用MySQLi或PDO。
答案 1 :(得分:0)
您可能错过了查询中的引号:
$check = "SELECT * FROM info WHERE num = \"$number\" AND cnic = \"$cnic\"";
由于字段可能是文本字段(varchar或类似字段),因此您需要告诉您要比较的值的限制在哪里。
此外,如果您需要在任何值匹配时跳过保存,则应使用OR:
$check = "SELECT * FROM info WHERE num = \"$number\" OR cnic = \"$cnic\"";