prevent duplicate entry data still no function - php

i have tried to prevent the duplicate data at my project.
but until now it still make duplicate.
i try this code but still not work:
$cek_user= "SELECT Model, Serial_number, Line FROM inspection_report WHERE Model='".$Model."' AND Serial_number='".$Serial_number."' AND Line='".$Line."'";
$cek_data=mysql_num_rows($cek_user);
if($cek_data!=0){
echo "Data already exists!";
}
else{
$sql = "INSERT INTO inspection_report ";
$sql.= "(Model, Serial_number, Line, Shift, Inspection_datetime, Range_sampling, Packing, ";
$sql.= "Accesories, Appearance, Tuner, General_operation, Remark, ";
$sql.= "NIK) ";
$sql.= "VALUES ('";
$sql.= $Model."','".$Serial_number."', '".$Line."','".$Shift."','".postVar('insp_date')." ".postVar('time')."','".$Range_sampling."','".$Packing."','";
$sql.= $Accesories."','".$Appearance."','".$Tuner."','".$General_operation."','".$Remark."','";
$sql.= $NIK."')";
//echo $sql;
$result=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
//echo $result;
}
mysql_close($dbc);
}
but still not work,please help.

This will not prevent duplicates unless your table also has a UNIQUE constraint somewhere allowing the database to determine what you mean by a duplicate. If you have such a constraint, perhaps you could post your table definition.

You can do a select before insert,
eg. Select id from table where serial_number = '$serial_number'
If mysql_num_rows equals 0, do insert. This assumes serial_number is unique for each row.
$sql = "SELECT ID FROM inspection_report WHERE Serial_number = '$Serial_number'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == 0){
$sql = "your insert sql..."
$result = mysql_query($sql);
}

You do realize your're running the INSERT query twice, right?
if ( mysql_query($sql) ) {
^^^^^^^^^^^--- here
[.... snip ....]
}
$result=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
^^^^^^^^^^^--- and here
As well, you should look into using HEREDOCs to build your query string. That long chunk of string concatenation and quote-soup you've got could look like this with a HEREDOC:
$insp_date = postVar('insp_date') . ' ' . postVar('time');
$sql = <<<EOL
INSERT INTO inspection_report
(Model, Serial_number, Line, Shift, Inspection_datetime,
Range_sampling, Packing, Accesories, Appearance, Tuner,
General_operation, Remark, NIK)
VALUES (
$Model, $Serial_number, $Line, $Shift, $insp_date,
$Range_sampling, $Packing, $Accesories, $Appearance, $Tuner,
$General_operation, $Remark, $NIK)
EOL;
every so slightly more readable.
edit/comment followup:
You're running the query twice, in the spots where I've put the '^^^^^--- here' lines.
First instance: if ( mysql_query($sql) ) {
Second instance: $result = mysql_query($sql) or die.......
You haven't changed the contents of $sql between the two mysql_query() calls, so when you do the second call, it runs the exact same query string, which is your INSERT query. So you end up inserting the data TWICE.
Beyond that, your error handling is atrocious. Scanning an error string for a particular string is the wrong way to go about it. The error text might change (think of what would happen if your code runs on a server running in (say) a German location, which has localized error messages and spits out "Doppelter eintrag für ..." instead of "Duplicate entry for". What you should have is something like this:
$sql = "... your query here ... "
$result = mysql_query($sql); // if query fails, this returns FALSE
if ($result === FALSE) {
die("MySQL error: " . mysql_error());
}
If you need to check for a particular error that could be corrected by your code, you can use mysql_errno() to retrieve the server error code, and work from there. Using your example, 'Duplicate entry' is error # 1062 (full error codes documented here), so you'd do
if (mysql_error() == 1062) {
... handle error here ...
}

first of all:
ALTER inspection_report ADD UNIQUE(Model, Serial_number, Line);
Then:
$sql = "INSERT IGNORE INTO..........";

Related

how do I check if a username is unique (php, MySQL) [duplicate]

I've looked for similar questions with no success.
I have this piece of code:
form1.php
$query = "INSERT INTO table1 ";
$query .= "(fname, lname, mail)";
$query .= " VALUES ";
$query .= "('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query) or die ("Query Failed: " . mysql_error());
And I want that the script will check if the value inserted exists in the corresponding column, and throw an error if it does. any ideas?
Create a UNIQUE key on the fields you care about, and detect the integrity error after the fact.

Mysql testing to see if an entry already exists [duplicate]

I've looked for similar questions with no success.
I have this piece of code:
form1.php
$query = "INSERT INTO table1 ";
$query .= "(fname, lname, mail)";
$query .= " VALUES ";
$query .= "('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query) or die ("Query Failed: " . mysql_error());
And I want that the script will check if the value inserted exists in the corresponding column, and throw an error if it does. any ideas?
Create a UNIQUE key on the fields you care about, and detect the integrity error after the fact.

copying data from table to table: validate mysql query

How would I go about validating this query? Currently, I getting some omissions where one row hasn't copied over so I need a bombproof method to check and correct. Query:
$query = "
SELECT *
FROM $UID
";
$result = mysql_query($query)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$q = $row['QID'];
$a = $row['answer'];
$c = $row['comment'];
$query = "
INSERT INTO a (UID, QID, answer, comment)
VALUES ('$UID', '$q', '$a', '$c')
";
mysql_query ($query)or die(mysql_error());
}
Thanks.
You can do this in a single query.
INSERT INTO a (UID, QID, answer, comment)
SELECT '$UID', QID, answer, comment FROM `$UID`
As its an atomic operation all the data will be copied in one shot. However you can still verify by using mysql_info function. It'll give output like following.
Records: 23 Duplicates: 0 Warnings: 0
Here Duplicate is the number of rows there were discarded due to duplicate key. If both Duplicates and Warning are 0 you can say query was successful.

Check if value exists before inserting into MySQL DB in a PHP script

I've looked for similar questions with no success.
I have this piece of code:
form1.php
$query = "INSERT INTO table1 ";
$query .= "(fname, lname, mail)";
$query .= " VALUES ";
$query .= "('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query) or die ("Query Failed: " . mysql_error());
And I want that the script will check if the value inserted exists in the corresponding column, and throw an error if it does. any ideas?
Create a UNIQUE key on the fields you care about, and detect the integrity error after the fact.

Database INSERT does not take place

My code is as follows:
<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
if($count==0)
{
$sql = "update Messages set up=up+1 where mes_id='$id'";
mysql_query($sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$id','$ip')";
mysql_query($sql_in) or die(mysql_error());
echo "<script>alert('Thanks for the vote');</script>";
}
else
{
echo "<script>alert('You have already voted');</script>";
}
$result=mysql_query("select up from Messages where mes_id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
echo "<img src='button.png' width='110' height='90'>";
echo $up_value;
}
?>
My problem is that the insert process does not take place at all. The script tags echos an alert box. Even the img tag is echoed to the web page. But the insert process does not take place. The config file is fine.
Note: This code works on my local machine which has PHP 5.3 but it does not work on the server which has PHP 5.2.
The only explanation is that the $count==0 check is false. Try with this workaround:
$ip_sql=mysql_query("select count(*) from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$rc=mysql_fetch_row($ip_sql);
$count=$rc[0];
instead of:
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
Have you tried messing around with the quotes? Someone please correct me if I'm wrong, but AFAIK, variables within single quotes don't get expanded in PHP.
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='".$id."' and ip_add='".$ip."'");
Looking at the answers and comments, it's time to get old school:
$sql = "update Messages set up=up+1 where mes_id='$id'";
echo $sql . '<br>';
mysql_query($sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$id','$ip')";
echo $sql_in . '<br>';
mysql_query($sql_in) or die(mysql_error());
echo "<script>alert('Thanks for the vote');</script>";
What are you looking for?
You are putting values in for $id and $ip - maybe one of them is empty or contains a character that is making the result "odd" in some way. By taking a good look at the raw query that you are about to execute, you'll see if the variable parts of it are upsetting things.
You're not checking if the first query succeeds:
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
There's no ... or die(mysql_error()) there, but this is most likely not the problem, because if the query was failing, you'd get an "invalid statement handle" type error when you do the mysql_num_rows() call immediately afterwards. As a stylistic tip, I'd suggest rewriting the first query as follows:
SELECT COUNT(*) FROM Voting_IP
WHERE (mes_id_fk = $id) AND (ip_add = $ip)
You're not using any of the retrieved values, just the row count, so there's no point in doing a "select *" type query, which forces the database to do at least SOME processing on all the possible values. If this system scales to very large numbers of votes and IPs, using the count() version will be more efficient.
You say the insert doesn't take place, but don't say which alert() occurs, which means either there's an error with the insert query, or your first query returns 0, and the whole block with the insert query is skipped.
Have you tried manually running the update/insert queries? You're not checking if the update succeeds, as there's no or die(mysql_error()) afterwards. Perhaps there's a foreign key error, a syntax error, etc...
If you're updating an entry based on an ID, then obviously you want to update and insert when the count is NOT zero.... or greater than zero,.. or 1
Simply taking out the == 0, should fix it
if($count)
{
$sql = "update Messages set up=up+1 where mes_id='$id'";
mysql_query($sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$id','$ip')";
mysql_query($sql_in) or die(mysql_error());
echo "<script>alert('Thanks for the vote');</script>";
}

Categories