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
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.
Is not giving me any error, I am already linked with server but I am still unable to get it work.
It's still unable to add message, do you see any errors?
function pridaj_tovar() {
if ($link = spoj_s_db()) {
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES".
"('$_POST['nazov']', '$_POST['kategorie']', '$_POST['mesta']',' $_POST['cena']', NULL,'$_POST['popis']')";
$result = mysql_query($sql, $link);
if ($result) {
// unable to add
echo '<p>inserting was successful.</p>'. "\n";
} else {
// unable to add!
echo '<p class="chyba">Nastala chyba pri pridávaní tovaru.</p>' . "\n";
}
mysql_close($link);
} else {
// NEpodarilo sa spojiť s databázovým serverom!
echo '<p class="chyba">NEpodarilo sa spojiť s databázovým serverom!</p>';
}
}
This is how you should handle field and table names with spaces,dashes (etc) :
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES".
"('Something', 'Something1', 'word', '50', NULL, 'anotherword')";
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES". "
('{$_POST['nazov']}', '{$_POST['kategorie']}', '{$_POST['mesta']}','{$_POST['cena']}',
NULL,'{$_POST['popis']}')";
You have several problems in your way of making query.
Firstly, your table name is quite non standard (Auto-Moto) so you might need to add quotes around it.
Secondly, it is always a good practice to add some space on proper locations so you could change:
"VALUES"
with
" VALUES "
But you need to provide which error you have received and your table structure.
You missed a lot of space in your Query :
Copy this :
$sql = "INSERT INTO Auto-Moto ".
"(Tovar, Kategoria, Mesto, Cena, ID, Popis) ".
"VALUES ".
"('Something', 'Something1', 'word', '50', NULL, 'anotherword')";
If you want to see an error message change this line:
$result = mysql_query($sql, $link);
To this:
$result = mysql_query($sql, $link) or die ("Error in query: $query. " . mysql_error());
But you should really learn to use mysqli_* extensions since mysql_* extensions—such as what you are using—will be depreciated in PHP 5.5. So change that to this:
$result = mysqli_query($sql, $link) or die ("Error in query: $query. " . mysqli_error());
And be sure to change any other mysqli_* extensions you code might have in place, such as in the spoj_s_db() function you are calling as the $link for a DB connection.
Additionally, your $sql has a few formatting errors. Try this instead:
$sql = "INSERT INTO Auto-Moto"
. " (Tovar, Kategoria, Mesto, Cena, ID, Popis)"
. " VALUES"
. " ('Something', 'Something1', 'word', '50', NULL, 'anotherword')"
;
Note the spaces in the query around the . " concatenation strings. In your original query the formatting had no spaces at all. Which would cause MySQL to choke on the query.
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.
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.
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..........";