简体   繁体   English

在允许INSERT尝试之前,检查mysql表的数据

[英]dupe checking mysql table for data before allowing INSERT attempt

I am trying to implement a data duplication check on user's inpout from html form before inserting it into mysql DB with the following code (largely lifted from: Best way to test if a row exists in a MySQL table ): 我试图从html表单中实现对用户输入的数据复制检查,然后使用以下代码将其插入到mysql DB中(很大程度上取消了: 测试MySQL表中是否存在行的最佳方法 ):

$serialNo = $_POST['serialNo'];

$sqldupe = "SELECT EXISTS(SELECT 1 FROM eqpt WHERE serial = '$serialNo')";

    if (mysqli_query($dbcon, $sqldupe)) {
        die('RECORD already exists');
    }

But I keep getting the error message even when I try entering a $serialNo that does not exist in the DB table eqpt. 但即使我尝试输入数据库表eqpt中不存在的$ serialNo,我仍然会收到错误消息。

I do have the serialNo column in the table protected with the UNIQUE option to prevent duplicate entries. 我确实在表中使用UNIQUE选项保护了serialNo列,以防止重复输入。 So this dupe check is more for a way to provide the user with a clue as to why their attempted insert was rejected if the serialNo entered is already in the DB. 因此,这种欺骗检查更多的是为用户提供一个线索,告诉他们如果输入的serialNo已经在DB中,他们的尝试插入被拒绝的原因。

I think I have a grasp of the snippet, but admit that because I have not touched sql/php in over a decade I need to get RTM to shake off some of the rust. 我想我已经掌握了这个片段,但承认因为我十多年来没有触及sql / php我需要让RTM摆脱一些生锈。 But if there is a quick/obvious fix to the problem here I would sure appreciate the help. 但如果有一个快速/明显的解决方案,我肯定会感谢你的帮助。

For mysqli_query function the return value will be true because "successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it will return a mysqli_result object. For other successful queries it will return TRUE. FALSE on failure" 对于mysqli_query函数,返回值为true,因为“成功的SELECT,SHOW,DESCRIBE或EXPLAIN查询将返回一个mysqli_result对象。对于其他成功的查询,它将返回TRUE。失败时返回FALSE”

Your SQL will always be successful because it is either returning 1 if exists or 0 if not. 您的SQL将始终成功,因为如果存在则返回1,否则返回0。 Removing the Exists will return no result if it doesn't exist and one if you do meaning the rest of the code will work. 如果存在,则删除存在将不返回任何结果,如果您确实意味着其余代码将起作用,则删除存在的结果。

Solution: 解:

$serialNo = $_POST['serialNo'];

$result = mysqli_query("SELECT EXISTS(SELECT 1 FROM eqpt WHERE serial = '$serialNo') AS found");

$value = $result->fetch_object();

if ($value->found) {
  die('RECORD already exists');
}

You can try this 你可以试试这个

$serialNo = $_POST['serialNo'];

 $sqldupe = "SELECT serial FROM eqpt WHERE serial = '$serialNo'";
if (mysql_num_rows(mysql_query($dbcon, $sqldupe)) > 0) {
    die('RECORD already exists');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM