简体   繁体   中英

MYSQL - Only insert record if it does not already exist?

I'm a noobie at mysql... but I'm trying to get this to check for a duplicate record based on the serialkey AND program. The record can only be submitted if the serialkey has not been submitted for that specific program already. 1 unique key is allowed PER program.

num is the unique number for each record

I had everything working properly with the record being submitted, BESIDES this duplicate check. Remember, I want the key to be allowed to be submitted multiple times, but ONLY once PER program.

 <?php $title = "Product Key Submission"; $con=mysqli_connect("URL HERE","USER HIDDEN","PASS HIDDEN","DB"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // escape variables for security $firstname = mysqli_real_escape_string($con, $_POST['firstname']); $lastname = mysqli_real_escape_string($con, $_POST['lastname']); $email = mysqli_real_escape_string($con, $_POST['email']); $program = mysqli_real_escape_string($con, $_POST['program']); $key = mysqli_real_escape_string($con, $_POST['serialkey']); $time = time(); $registered = date('Ymd g:i:sa',$time); if ($firstname == ""){ echo "<h1>BLANK FIELD FOR NAME</h1>"; mysqli_close($con); } else { //###################### CHECK IF RECORD EXISTS ###################### $query = mysqli_query("SELECT count(*) AS 'num' FROM `product_keys` WHERE `program` = '$program' AND `serial_key` = '$key'"); $num = mysqli_fetch_assoc($query); if ($num['num'] >= 1) { echo "You have reached your limit of key submissions."; } //###################### CHECK IF RECORD EXISTS ###################### else { echo "THE KEY WILL BE SUBMITTED..."; 

You can leave your code the way it is, with the exception of:

Do:

$query = mysqli_query($con,"SELECT...

The problem is that you are not connecting with DB.


You may also have error reporting's default set to off.

It should have thrown the following warnings:

Warning: mysqli_query() expects at least 2 parameters, 1 given in...

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in...

Meaning that mysqli_query() expects at least 2 parameters is looking for a DB connection and the second warning message is because it enchains with the first warning and continues until it finds some form of success to stop the process.

which is why it was going to your

else {
        echo "THE KEY WILL BE SUBMITTED...";

condition.

Add error reporting to the top of your file(s) which will help during production testing.

error_reporting(E_ALL);
ini_set('display_errors', 1);

as well as or die(mysqli_error($con)) to mysqli_query() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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