Reputation: 3
I am trying too input a new number into a databasee only if it does not already exist, in order to do this, I am doing the following
if (isset($_POST['Number'])) {
$number = ($_POST['Number']);
$NCheck = "SELECT COUNT(*) FROM `DS_Numbers` WHERE `Number` = '$number' ";
$stmt = $dbCon->prepare($sql);//* prepared statement for result which populates table
$stmt->execute();
$result = $stmt->fetchColumn(0);
if($result > 0){ // if there is a value then block
$ENumber = "This Number already exists";
$errors[] = 'error';
} else {
echo "number done";// echo statement to see that it has reached this
$number1 = ($_POST['Number']);
}
} else {
$errors[] = 'error';
$ENumber = "Please enter only digits from 0-9";
}
What is currently happening is that my PDO statement is not returning, so my result value is always 0, but none of my research has shown that I have an issue with it
any suggestions on where I am going wrong? I am getting Number from an HTML form on the page, no issues on that side.
Upvotes: 0
Views: 44
Reputation: 1
If the number must be unique in the table then you should probably add a UNIQUE constraint to the column. You can then just insert the number and if it was not unique the database will return a 'duplicate key' error.
If you use the 'check-first-insert-later' method you are open to race conditions; if two processes try to insert the same number at the same time they will both run the select at the same time and they will both get zero and try to insert, which without a unique constraint will work for both.
Upvotes: 0
Reputation: 5397
First thing to notice is that you are writing your query in a variable called $NCheck
, not $sql
.
So this line
$stmt = $dbCon->prepare($sql);
should be
$stmt = $dbCon->prepare($NCheck);
Also please note that one of the main advantages in using PDO is to use bound parameters, but you are not doing this and you are in fact exposed to SQL injection since you are just adding that value you get in POST in the query.
Upvotes: 1