Check that data in a SQL table already exists - 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.
This is what I have so far:
$sql = "INSERT INTO user_data (product_name, code, comments)
VALUES ('$_POST[product_name]','$_POST[code]','$_POST[comments]')";

This is terrible SQL coding practice and, as stated before, is vulnerable to SQL Injection Attacks but something along these lines should work.
$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]') ";

The best way to do this is by adding a uniqueness constraint to your table itself. This way you can prevent duplicate records from being added.
In your case I would go with this:
ALTER TABLE `user_data` ADD UNIQUE (
`product_name`
)
Also, you could check for the record before you add it:
$sql="SELECT count(*) AS number FROM user_data WHERE product_name LIKE '".$_POST['product_name']."'";
If the column "number" 1 (or bigger), you know it already exists. Also when you get 2, or bigger, you will know that you already have duplicate records.

Related

error in insert sql statement

this is sign up form pls help me to solve this error
ERROR: Could not able to execute sql insert statement
INSERT INTO customer(customer_id,customer_name,customer_email,customer_password) VALUES (null,'','','').Column 'customer_id' cannot be null
//check connection
if($link===false){
die("ERROR: could not connect. " . mysqli_connect_error());
}
//Escape user inputs for security
$customer_id = mysqli_real_escape_string($link, $REQUEST['customerid']);
$customer_name = mysqli_real_escape_string($link, $REQUEST['Name']);
$customer_email = mysqli_real_escape_string($link, $REQUEST['Email']);
$customer_password = mysqli_real_escape_string($link, $REQUEST['Password']);
//attempt insert query execution
$sql="INSERT INTO customer(customer_id,customer_name,customer_email,customer_password) VALUES (null,'$customer_name','$customer_email','$customer_password')";
if(mysqli_query($link,$sql)){
echo "records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql.".mysqli_error($link);
}
mysqli_close($link);
?>
It says in your error message that the column customer_idcan not be null.
Looking at your query VALUES (null,'$customer_name','$customer_email','$customer_password')"; the values start after the parenthesis. So your first column is customer_id and the first value is null.
The error message tells you that your table is not setup to allow for customer_id to be null. So you either have to change to database table structure or your query. As it is about an ID I suggest you change your query.
If customer_id is an auto incremented field you should simply not set it (remove it from your query)
Edit:
It is not usual to have an identifier set to varchar. Seeing something like customer_id lets most people assume that they are dealing with an integer. The easiest approach would be to make that table column an integer with auto increment in your database (in most cases such a field would also be primary key).
Seeing that your table requires the field customer_id it can not be left out from your query and you would have to generate / create an adequate identifier for your customer. A workaround for your current table structure:
$sql="
INSERT INTO
customer
(customer_id,customer_name,customer_email,customer_p‌​‌​assword)
VALUES (
(select count(customer_id) from customer)+1,'$customer_name','$customer_email','$customer_pa‌​ssword‌​')";
Edit 2:
Some additional information on database column data types: mysql char vs. varchar and mysql integer
if you later on have a more complex database and query multiple tables at once to gather your data you will have to rely on your indices and realtions (foreign keys) to get the results fast. IE: having a join on your customer_id is rather slow. setting it to char lets it operate faster due to varchar having a variable length. I have not yet tested the performance regarding char and integer
You need to pass customer_id instead of null in the query, e.g.:
$sql="INSERT INTO customer(customer_id,customer_name,customer_email,customer_password)
VALUES ('$customer_id','$customer_name','$customer_email','$customer_password')";
You can remove customer_id column like below,
$sql="INSERT INTO customer(customer_name,customer_email,customer_password)
VALUES ('$customer_name','$customer_email','$customer_password')";
If you set customer_id as auto increment in database there no need to include it in query
If your customer_id is an autoincrement id of your customer table then, no need to put it inside your INSERT statement.
Simply run without customer_id
$sql="INSERT INTO customer(customer_name,customer_email,customer_password)
VALUES ('$customer_name','$customer_email','$customer_password')";
Ok. Let me explain you somethings.
Case 1 :
If your customer_id is an integer type and you have not put anything in default value then it will not allow you to insert a null into that field. For that, you need to set default value as NULL.
Case 2
If your customer_id is an autoincrement id of customer table then you can't set null into it during a SQL statement.

Updating a row with query language, mysql, php

I have a basic question for you experts,
I want to update a row in mysql database by using the User_Id of an entry. I created User_Id as auto increment, primary key. Now for the last user I calculated its necessary variables, now I want to add that variable to the last user's necessary column through its User_id.
The name of the variable I want to add is $improvement. I wrote the code below, however I dont now how to do that depending on its User_Id.
$sql = "
UPDATE users
SET Improvement='$improvement'
WHERE ... )
";
mysql_query($sql, $accounts);
I dont know what to write to the "..." part in the code. Please give me feedback if you see a problem in my question. I can give my table if you need.
mysql updating last inserted id
I guess I found the answer in that link:
$sql = "
UPDATE users
SET Improvement='$improvement'
WHERE User_id = LAST_INSERT_ID() )
";
However I am not sure if "SET Improvement='$improvement'" part is the correct syntax
If your user_id is primary index then you can use
$sql = "
UPDATE users
SET Improvement='$improvement'
order by user_id DESC limit 1 )
";
mysql_query($sql, $accounts);

PHP Code for fetching one row in MSSQL in each registration process

Here is my query part of my registration PHP form.
columns account,password,email and age could be inserted by registration page user and they work well but, the column account_id needs to be increased by 1 automatically with each registration process.
Table name is Account not account and column name is account_id.
$query = "INSERT Account( account,password,email,pk_,type_ ) VALUES('$username','$converted_password','$email',1,'$age')";
$query_total = mssql_query("SELECT COUNT(account_id) FROM Account");
$results_check = mssql_query($query_check);
$results_total = mssql_fetch_row($query_total);
$result_total = $results_total['0'];
It gives me a NULL value for the (account_id) column and INSERT fails.
Perform the following query on your database: (Mysql based query!! not Mssql!!)
ALTER TABLE `Account` CHANGE `account_id` `account_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY;
this wil result in an autoincrement.
If this fails you'll probably already own duplicates, you'd have to solve this first. There are many ways for this, though it mostly depends upon connections with other tables.
After that for each insert into account do not include the account_id.
use the mysql query:
select LAST_INSERT_ID();
to retrieve the last inserted id.
within PHP you can use http://nl1.php.net/mysql_insert_id though i'd highly advice you to start looking into http://www.php.net/PDO or http://www.php.net/mysqli with prepared statements.
Because as far as i've understood in the next version of PHP the basic Mysql functions will become deprecated. And prepared statements are better/safer. (If properly used)
Set account_id to auto increment in MySQL and just don't shoot anything to the MySQL database for the field account_id. MySQL will automatically create a new ID.
Read something about auto increment:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
*edit:
Also change
$query = "INSERT Account( account,password,email,pk_,type_ ) VALUES('$username','$converted_password','$email',1,'$age')";
to
$query = "INSERT INTO Account(account,password,email,pk_,type_) VALUES('$username','$converted_password','$email',1,'$age')";

Database normalization and lazy development

I believe the question have emerged as my irritation of doing twice as much work as I could imagine is necessary.
I accept the idea that I could be lacking experience with both MySQL and PHP to think of a simpler solution.
My issue is that I have several tables (and I'd might be adding more) and of these is a parent table, only containing two fields - an id (int) and a name identifying it.
At this moment, I have seven tables with at least 15 fields in each one. Every table has a field, containing the id which I can link to the parent table.
All of these data isn't required to be filled - you will just have to create that one entry in the parent table. For the other tables, I have separate forms.
Now, these forms are made for updating the data in the fields, which means I have to pull out the data from the table if any data is available.
What I would like to do is when I receive the data from my form, I could just use an UPDATE query in my model. But if the table I want to update doesn't have an entry for that specific id, I need to do an insert.
So, my current pseudo code is like this:
$sql = "SELECT id FROM table_x WHERE parent_id = ".$parent_id;
$res = $mysql_query($sql);
if( mysql_num_rows($res) == 1 )
{
$sql = "UPDATE table_x SET ... WHERE parent_id = ".$parent_id;
}
else
{
$sql = "INSERT INTO table_x VALUES ( ... )";
}
mysql_query($sql);
I have two do this for every table I have - can I do something different or smarter or is this just the way it has to be done? Cause this seems very inefficient to me.
Use
INSERT ... ON DUPLICATE KEY UPDATE Syntax
It will insert if record not found,
otherwise, it will update existing record,
and you can skip the check before insert - details
This assuming relation for each 7 table to the parent table is 1:1
Or use REPLACE instead of INSERT - it's an insert, but will do an DELETE and then INSERT when a unique key (such as the primary key) is violated.
in mysql you can do this:
INSERT INTO table
(
col1,
col2
) VALUES(
'val1',
'val2'
) ON DUPLICATE KEY UPDATE table SET
col2 = 'val2'
take a look at the documentation for more information
mysql_query("UPDATE table table_x ..... WHERE parent_id=".$parent_id);
if (mysql_affected_rows()==0) {
mysql_query("INSERT INTO .....");
}

mysql DB not adding rows with similar elements

i have created a DB with 3 columns:
aid, qid and message.
aid is a foreign key which will be commond with another table.
comments is a varchar which stores user comments
its partially working. the problem is aid is not adding duplicate values.
suppose i want to add comments related to specific aid. there are 18 aid's in all. and i want to filter the comments according to aid's. the table is not adding a duplicate aid.
this is the query I am using in php:
$query = "UPDATE answers SET acount = acount + 1 WHERE aid = $vote";
$result = mysql_query($query);
$cadd = "INSERT INTO comments (aid, msg) VALUES ('$vote','$comment')";
mysql_query($cadd);
what am i doing wrong. i am attaching a screenshot of the DB structure.
caution: extreme n00b.
It looks like aid is your primary key, which should be unique.
Show table comments. I would guess the PK there is aid.
b.t.w your code is vulnerable to sql injection (unless this is only for the sake of debugging).

Categories