scriptz
scriptz

Reputation: 515

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):

$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.

I do have the serialNo column in the table protected with the UNIQUE option to prevent duplicate entries. 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.

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. But if there is a quick/obvious fix to the problem here I would sure appreciate the help.

Upvotes: 3

Views: 90

Answers (2)

OutOfBorder
OutOfBorder

Reputation: 66

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"

Your SQL will always be successful because it is either returning 1 if exists or 0 if not. 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');
}

Upvotes: 3

Adhan Timothy Younes
Adhan Timothy Younes

Reputation: 570

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');
}

Upvotes: 1

Related Questions