Prevent duplicates being added to database table via PHP form - php

I want to log what a user enters into a PHP form, and make sure they are not entering data that already exists in a database table.
I have the code already that enters the data into the table from user input, but I'm not sure how to check for duplicates. For example I want to check that there is no product under the same name being added again.
$sql = "
INSERT INTO user_date
SELECT
product_name = '$_POST[product_name]'
,code = '$_POST[code]'
,comments = '$_POST[comments]'
WHERE
NOT EXISTS(SELECT * FROM user_data WHERE product_name = '$_POST[product_name]') ";
But I get an error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= 'fdgfdg' code = 'fdgdfg' WHERE NOT EXISTS(SELECT *' at line 4
I'm aware of the security issues. Its not a live system but just to learn from it.

If you don't want to have duplicate insert then use IGNORE at end of insert statement
$sql = "
INSERT INTO user_date
values
('$_POST[product_name]'
,'$_POST[code]'
,'$_POST[comments]')
ON DUPLICATE KEY IGNORE";
So this way might help you
$result = mysql_query("SELECT * FROM user_data WHERE product_name = '$_POST[product_name]'");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// do something
}
else {
// do something else
}

Related

PHP: Error on Update statement with subquery

I have a page that updates the data of a specific user. The user has position, which is a foreign key. The query update (below) works fine without the position, but with the position I get the following error.
Query :
$queryUpdate = "UPDATE visitorsystem.employee SET idNumber = '$idNumber', name = '$name',
surname = '$surname',
position = 'SELECT positionid FROM visitorsystem.position WHERE positionName LIKE '%$position%'',
email = '$email'
WHERE employeeid = '$empId'";
$resultUpdate = mysqli_query($connection,$queryUpdate)
or die("Error in query: ". mysqli_error($connection));
Error in query: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near 'SELECT positionid FROM visitorsystem.position WHERE
positionName LIKE '%Informat' at line 3
I have tried to work my way around by using inner join as I have seen some solutions given here on stack but nothing has worked. Any Suggestions ?
Subqueries go within regular parens, not quotes, so in a general sense:
SELECT x FROM y WHERE z IN (SELECT z FROM a)
Single and double quotes (by default) are only for string values.

MYSQL Error #1064 - Update multiple rows

I have to update a dynamic form where the user can add, deleted and update questions in a questionnaire. I've created all my code that will generate one query which is executed once at the end.
I get a problem when I try to update more than one question at the same time (INSERT and DELETE works like a charm).
$query = ''; // append every thing to update in this variable
// for each questions check if needs to be modify, if yes append.
$query .= 'UPDATE `questionnaire` SET `id_category` = '.$categoryValue.' WHERE `id` = '.$idQuestion.'; '
Example of an output
UPDATE `questionnaire` SET `id_category` = 1 WHERE `id` = 1; UPDATE `questionnaire` SET `id_category` = 3 WHERE `id` = 2;
Submit to the database;
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->close();
}
If I only have one UPDATE, it works like a charm. As soon that I have 2 updates, I get this MYSQL error :
errno : 1064
error : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE `questionnaire` SET `id_category` = 3 WHERE `id` = 2' at line 1
Does anyone have an idea why it only happens when I have two UPDATE ? If yes, how should I fix this.
As suggested by Mike W (Thank you), I changed
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->close();
}
for
if ($mysqli->multi_query($query)) {
// Success
}

SQL to only insert a new row into MYSQL table if id does not already exist

I have a mysql database table called sales with the columns id | timeStamp | timeString | EAN where I want to insert new values if the ID does not already exist in the table. For example I may want to add:
9997a04fe3f932bf6f8e9d88f4b8dc96 | 0000003082461 | 11:07 (Thu. 22 May. 2014 | 1400716800
to the database table if the id '9997a04fe3f932bf6f8e9d88f4b8dc96' has not already been entered before.
The SQL I have written so far looks like this: (using 1234 as dummy values, there is already a row in the table with and id of 1)
INSERT INTO `sales`(`id`, `timeStamp`, `timeString`, `EAN`) VALUES (1,2,3,4)
WHERE NOT EXISTS (
SELECT `id` FROM `sales` WHERE `id` = '1'
)
Please help me to get this SQL statement working. At the moment this reports a syntax error of:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS ( SELECT `id` FROM `sales` WHERE `id` = 1 ' at line 2
Add unique index to ID column and then use INSERT IGNORE statement
Before the INSERT Statement you need to check whether the data exist or not. If exits just give a message to user data already exist or whatever you want.
Like this
$result = mysqli_query ($con,"SELECT COUNT(id) FROM sales WHERE (id='$id')");
$row = mysqli_fetch_row($result);
$total_records = $row[0];
if($total_records == 0)
{
INSERT INTO sales(`id`, `timeStamp`, `timeString`, `EAN`) VALUES
($id,$timestamp,$timestring,$Ean);
} else
{
--------------Enter-----
------------Error message------
}

mysqli insert - but only if not a duplicate [duplicate]

This question already has answers here:
if not exists insert in MySql
(2 answers)
Closed 9 years ago.
I'm a Java developer who just got handed the task of "some quick easy DB stuff" - except I don't know much about PHP/MySQL...I need to insert a record into a DB - but only if the email field doesn't match one that already exists in the DB. Here's what I've gleaned so far for my PHP code:
// Grab the values from the HTML form:
$newUserName = $_POST['newUserName'];
$newUserName = $mysqli->real_escape_string($newUserName);
$newUserEmail = $_POST['newUserEmail'];
$newUserEmail = $mysqli->real_escape_string($newUserEmail);
// Now search the DB to see if a record with this email already exists:
$mysqli->query("SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");
Now I need to see if anything came back from that search - meaning the email already exists - and if so I need to alert the user, otherwise I can go ahead and insert the new info into the DB using:
$mysqli->query("INSERT INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
Any ideas?
Working from your code, this should point you in the right direction. there are, perhaps, better ways to structure your database that will make better use of it.
<?php
$mysqli = new mysqli("localhost", "iodine", "iodine","iodine");
// Grab the values from the HTML form:
/*
$newUserName = $_POST['newUserName'];
$newUserName = $mysqli->real_escape_string($newUserName);
$newUserEmail = $_POST['newUserEmail'];
$newUserEmail = $mysqli->real_escape_string($newUserEmail);
*/
$newUserName = "Test User";
$newUserEmail = "test4#example.com";
// Now search the DB to see if a record with this email already exists:
echo "SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'", "\n";
$result = $mysqli->query("SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");
if (!$result) {
die($mysqli->error);
}
echo "num_rows = ".$result->num_rows."\n";
if ($result->num_rows > 0) {
echo "Duplicate email\n";
// do something to alert user about non-unique email
} else {
$result = $mysqli->query("INSERT IGNORE INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
if ($result === false) {echo "SQL error:".$mysqli->error;}
}
?>
Consider putting a unique index on this particular table. The following code will add the index and remove any current duplicates:
ALTER IGNORE TABLE `RegisteredUsersTable` ADD UNIQUE INDEX unique_email (`UserEmail`);
Once this is added, use INSERT IGNORE or INSERT...ON DUPLICATE KEY UPDATE. They will only preform the insert if there is no duplicates.
$mysqli->query("INSERT IGNORE INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
Mysql will throw an error because the email is already in the database. However, the IGNORE command is telling the script to not pay any attention to errors for this query because, in this case, you expect it for a duplicate row.
Also, there is a way to alert your user with a failure or success message, even with INSERT IGNORE. Use MYSQL LAST_INSERT_ID(). If an ID was given, it was inserted. If not, then the email was already there (or there was another error).
As for your first query, to soften the load on servers, use count() instead.
$mysqli->query("SELECT count(*) FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");
This way, you can just check if you've gotten a result higher than 1. If the result is greater than 1, then the username exists (Since a row was returned).
To check the data returned, you need to simply execute the statement, then fetch the results. Part of the fun is learning, so here's the documentation

PHP/MySQL Concat to a single column and Update other columns in table

Am trying to only concat new updates to column updates and UPDATE the values in the rest of the columns but I've hit bit of a snag that I can't seem to workout.
My SQL looks like this:
$query="Update tickets SET product='$product',
p='$p',
i='$i',
summary='$summary',
workaround='$workaround',
concat(updates,'$additional_update'),
status='$status',
raised_by='$raised_by',
updated_by_user='$updated_by' WHERE id='$id'";
the updates column is like a comments column, where new updates are meant to be appended to the existing text.
The error I'm getting on the web server:
Update tickets SET product='T-Box', p='00000817766', i='-', summary='Testing update field
\r\nAdding an update\r\ntesting if null works for update', workaround='n/a', concat(updates,' ','test2#18:53:17:second update/n'), status='Open', raised_by='No', updated_by_user='test2' WHERE id='223'
Running the query directly in MySQL:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(updates,'test2#18:53:17:second update/n'), status='Open', raised_by='No', updat' at line 1
Help is much appreciated!
You need to specify where the value of this statement concat(updates,'$additional_update') to be set.
Update tickets
SET product = '$product',
p = '$p',
i = '$i',
summary = '$summary',
workaround = '$workaround',
updates = CONCAT(updates,'$additional_update'), // <== see this
status = '$status',
raised_by = '$raised_by',
updated_by_user = '$updated_by'
WHERE id = '$id'
try this:
$query="Update tickets SET product='$product',
p='$p',
i='$i',
summary='$summary',
workaround='$workaround',
updates=concat(updates,'$additional_update'),
status='$status',
raised_by='$raised_by',
updated_by_user='$updated_by' WHERE id='$id'";

Categories