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

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.

Related

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.

Sending message back if table row has value

For example, have a query like this:
<?php
$sql = "INSERT INTO oppgave
(username, besvarelse, modulid)
VALUES
('$username', '$besvarelse', '$modulid');
";
mysql_query($sql, $tilkobling);
?>
How can I do this:
If modulid row is not empty, echo "you have sent this modul before";
Try this:
<?php
$sql = "INSERT INTO oppgave(username, besvarelse, modulid)
select '$username', '$besvarelse', '$modulid'
from dual
where not exists (select modulid from oppgave where modulid='$modulid')";
$result=mysql_query($sql, $tilkobling);
if(mysql_affected_rows()==0){
echo "Failed to insert duplicate modulid";
}else{
echo "inserted";
}
?>
In this SQL Query, it will allow insert only if $modulid isn't already exist in database table. Such situation you can also handle by applying UNIQUE constraint to table column (but remember, it allows NULL value at once)
Best way to do this, is by not allowing duplicates.You can do this with your SQL QUERY.Build your query by this:
$sqlString ="INSERT INTO oppgave('" . $username . "', '" . $besvarelse . "', '" . $modulid . "')
SELECT username, besvarelse, modulid
FROM oppgave
WHERE NOT EXISTS (SELECT *
FROM oppgave
WHERE modulid IS NULL)";
Please check all names and tablenames first ;)
Hope this helps.If this the answer, please mark as answer.

Prevent multiple data entries in MySQL

So here is the deal. I have looked around everywhere, and all other techniques relate to refreshing the browser, and methods to prevent the php page from resubmitting the post data. I am new to this (obviously :p) But anyways, my questions I believe is simple. I just want a method, possibly an if else statement that would check the post data entries, and if there is a match already in my table, than do not execute the query. I am not worried about querying all of the results of the table, as I only suspect this table will ever have 50-60 entries.
Here is the php page that handles the form submission:
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$submitDate = date("Y-m-d");
mysql_connect ("localhost", "abc", "123") or die ('Error: ' . mysql_error());
mysql_select_db ("members");
$query = "INSERT INTO persons (ID, firstName, lastName, email, city, state, submitDate)VALUES (
'NULL',
'".$firstName."',
'".$lastName."',
'".$email."',
'".$city."',
'".$state."',
'".$submitDate."'
)";
mysql_query($query) or die ('Error Updating database');
echo "Database Updated With: " .$firstName ." " .$lastName ." " .$email ." " .$city ." " .$state;
mysql_close($con);
Sorry, cant ever seem to get my php to format correctly with those code braces. Anyways. just to re-iterate, looking for a way to maybe based on the first and last name. if those already exist, then do not allow the submission of the data. I have tried a few if then statements but i do not think I am getting the concept down of comparing the result to my query. I hope this all makes sense!!!
I would suggest adding a UNIQUE index on the columns you want to have unique.
You can just use INSERT IGNORE INTO ... and let MySQL handle it.
$query = "INSERT IGNORE INTO persons (ID, firstName, lastName, email, city, state, submitDate) VALUES (
'NULL',
'".$firstName."',
'".$lastName."',
'".$email."',
'".$city."',
'".$state."',
'".$submitDate."'
)";
Is your problem only that refreshing the page resends the POST data? The pretty much standard way to prevent that is to redirect the browser after having processed the form data, like so:
header('Location: ' . $_SERVER['PHP_SELF']);
Keep in mind, changing headers has to be done before any output is sent to the browser, so this should be above your doctype, and be sure there is no white space before either.
One way of doing this is to make sure your table has appropriate primary keys set (firstname and lastname at least), and then just trying the insert and seeing whether it fails on duplicate. You can check the error message using the mysql_error() function for this purpose.
You can do a select on the database with those two fields to check if a row already exists, but if this is something that needs to be unique there should also be a unique index on those two columns in your MySQL table.
I had this issue as well. Basically what I did is before the insert, do a select on the criteria that would qualify as a duplicate and check for it to return; if it does not we are ok to enter.
$query = "SELECT COUNT(id) AS mycount FROM persons WHERE firstName = '".$firstnName."' AND lastName = '".$lastName."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if($row['mycount'] == 0) {
//Do insert
}

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.

prevent duplicate entry data still no function

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..........";

Categories