Display error message in php for MYSQL duplicate error - php

I am using UNIQUE Constraint in my table for two columns to prevent duplicate rows. If I try to insert a row with the same 2 columns I get
A Database Error Occurred Error
Number: 1062
Duplicate entry '62-88' for key
'subscription'
INSERT INTO subscriptions
(user_id, subscribed_to, date)
VALUES ('62', '88', '2011-07-11
19:15:13')
Filename:
C:\wamp\www\mysite\system\database\DB_driver.php
Line Number: 330
How can I return a php error, e..g Already subscribed! instead of displaying the mysql error?

Call mysql_errno() after your mysql_query() and check for 1062.
Note: It's a more common/intuitive solution to query the database first. See answer by Manocho.

I think you will need to run a query manually to check if the entry already exists in your database. so something like: SELECT COUNT(*) FROM subscriptions WHERE (user_id = '62' AND subscribed_to = '88'). If the count returned is > 0 then return the error, however you want it displayed.

http://php.net/manual/en/function.mysql-error.php I assume you are able to programatically obtain the MySQL error
http://www.php.net/manual/en/function.mysql-errno.php
http://dev.mysql.com/doc/refman/5.5/en/error-handling.html
Using the 3rd link, compare the mysql error or mysql errno to the list of errors and if the condition is met, provide your alternate error message.

To solve the error you can do this:
mysql_query($sql);
if (mysql_errno() == 1062) {
print "<script type=\"text/javascript\">";
print "alert('The informations are already inserted')";
print "</script>";
}

try this code :
$query = "INSERT INTO ".$table_name." ".$insertdata;
if(mysqli_query($conn,$query)){
echo "data inserted into DB<br>";
}else{
if(mysqli_errno($conn) == 1062)
echo "duplicate entry no need to insert into DB<br>";
else
echo "db insertion error:".$query."<br>";
}//else end

Related

PHP PDO If statement to check if field is empty in delete statement

Apologies if this has been asked before, but I havent found an answer that suits my needs.
I have a prepared statement to delete data from a table using user input:
$delete = $handler->prepare("DELETE FROM screenings WHERE
time = :time ORDER BY screeningid LIMIT 1; ");
$delete- >execute(array( ':time' => $screeningtime ));
I'm trying to add an if statement before the delete statement to first check if the record exits, and if so executes the delete statement otherwise echos an error message.
so far i've been trialling:
if(empty($row['column'])) {
echo "error";
}else {
//delete statement here
}
but to no avail, the error message prints out in all instances
You'd need to do a SELECT to detect if the row exists.
However, the result of the DELETE would return the number of rows affected, so you could just run it regardless, and then check if 0 or 1 or >1 rows were deleted. That would be $delete->rowCount()
http://php.net/manual/en/pdostatement.rowcount.php
<? Php
$delete->execute();
if ($delete->rowCount() >= 1)
echo 'ok';
else
echo 'error or not found';

How to execute 2 SQL queries one after the other using mysqli_multi_query in PHP

I was trying insert values simultaneously into MySQL database using mysqli_multi_query but it's not executing and going to if part showing alert message stating Record Insertion Failed.
Below is my PHP code with query
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
$sql_tableone = "INSERT into inverterlog (`id`,`timestamp`,`irradiance`,`ambienttemp`,`photovoltaictemp`,`pv1voltage`,`pv2voltage`,`pv3voltage`,`pv1current`,`pv2current`,`pv3current`,`pv1power`,`pv2power`,`pv3power`,`pv1energy`,`pv2energy`,`pv3energy`,`gridvoltagegv1`,`gridvoltagegv2`,`gridvoltagegv3`,`gridcurrentgc1`,`gridcurrentgc2`,`gridcurrentgc3`,`gridpowergp1`,`gridpowergp2`,`gridpowergp3`,`sumofapparentpower`,`gridpowertotal`,`gridenergyge1`,`gridenergyge2`,`gridenergyge3`,`socounter`,`gridcurrentdcgc1`,`gridcurrentdcgc2`,`gridcurrentdcgc3`,`gridresidualcurrent`,`gridfrequencymean`,`dcbusupper`,`dcbuslower`,`temppower`,`tempaux`,`tempctrl`,`temppower1`,`temppowerboost`,`apparentpowerap1`,`apparentpowerap2`,`apparentpowerap3`,`sovalue`,`reactivepowerrp1`,`reactivepowerrp2`,`reactivepowerrp3`,`opmode`,`latestevent`,`pla`,`reactivepowermode`,`overexcitedunderexcited`,`reactivepowerabs`,`inverter`)
values('','$newDate','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$emapData[7]','$emapData[8]','$emapData[9]','$emapData[10]','$emapData[11]','$emapData[12]','$emapData[13]','$emapData[14]','$emapData[15]','$emapData[16]','$emapData[17]','$emapData[18]','$emapData[19]','$emapData[20]','$emapData[21]','$emapData[22]','$emapData[23]','$emapData[24]','$emapData[25]','$emapData[26]','$emapData[27]','$emapData[28]','$emapData[29]','$emapData[30]','$emapData[31]','$emapData[32]','$emapData[33]','$emapData[34]','$emapData[35]','$emapData[36]','$emapData[37]','$emapData[38]','$emapData[39]','$emapData[40]','$emapData[41]','$emapData[42]','$emapData[43]','$emapData[44]','$emapData[45]','$emapData[46]','$emapData[47]','$emapData[48]','$emapData[49]','$emapData[50]','$emapData[51]','$emapData[52]','$emapData[53]','$emapData[54]','$emapData[55]','$inverter')";
$sql_tabletwo = "INSERT into data (`id`,`timestamp`,`gridpowertotal`,`inverter`) values ('','$newDate','$emapData[26]','$inverter')";
$sql= $sql_tableone.";".$sql_tabletwo;
$result = mysqli_multi_query( $con,$sql);
if (! $result ) {
echo "<script type=\"text/javascript\">
alert(\"multi query Record Insertion Failed.\");
</script>";
}
fclose($file);
}
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"four.php\"
/</script>";
//close of connection
mysqli_close($con);
}
}
If the id column is auto-incremented in the tables, then omit the column (and the empty value) from your query. Alternatively, you can use NULL (not quoted) if you are going to mention the column in your query.
Many, many people struggle to find the errors with their mysqli_multi_query() code block because it is not set up to properly output affected rows and errors.
I recommend having a look at a general purpose code block that will help to isolate troublesome queries, and read this answer.
It also looks like you are while-looping mysqli_multi_query()'s two queries. For efficiency, I recommend building up the full array of queries, finishing the loop, then calling mysqli_multi_query() only once.
p.s. Do any of your insert values have quotes in them? Prepared statements would help with that issue. Use the code block from my link and check the error message.
UPDATE: Here is my spoon-fed answer (Of course, I didn't actually test it before posting):
// I assume $newdate is not user declared and considered safe.
// I am using NULL for your auto-incremented primary key `id`.
// If you want to be assured that each pair has an identical `id`, perhaps use LAST_INSERT_ID() on second query of pair.
// establish variables for future use
$inverterlog_sql="INSERT INTO `inverterlog` (`id`,`timestamp`,`irradiance`,`ambienttemp`,`photovoltaictemp`,`pv1voltage`,`pv2voltage`,`pv3voltage`,`pv1current`,`pv2current`,`pv3current`,`pv1power`,`pv2power`,`pv3power`,`pv1energy`,`pv2energy`,`pv3energy`,`gridvoltagegv1`,`gridvoltagegv2`,`gridvoltagegv3`,`gridcurrentgc1`,`gridcurrentgc2`,`gridcurrentgc3`,`gridpowergp1`,`gridpowergp2`,`gridpowergp3`,`sumofapparentpower`,`gridpowertotal`,`gridenergyge1`,`gridenergyge2`,`gridenergyge3`,`socounter`,`gridcurrentdcgc1`,`gridcurrentdcgc2`,`gridcurrentdcgc3`,`gridresidualcurrent`,`gridfrequencymean`,`dcbusupper`,`dcbuslower`,`temppower`,`tempaux`,`tempctrl`,`temppower1`,`temppowerboost`,`apparentpowerap1`,`apparentpowerap2`,`apparentpowerap3`,`sovalue`,`reactivepowerrp1`,`reactivepowerrp2`,`reactivepowerrp3`,`opmode`,`latestevent`,`pla`,`reactivepowermode`,`overexcitedunderexcited`,`reactivepowerabs`,`inverter`) VALUES (NULL,$newdate";
$data_sql="INSERT INTO `data` (`id`,`timestamp`,`gridpowertotal`,`inverter`) VALUES (NULL,'$newDate'";
$tally=0;
$x=0;
// build all queries
while(($emapData=fgetcsv($file,10000,","))!==false){
++$x;
$sql[$x]=$inverterlog_sql; // start first query of pair
for($i=1; $i<56; ++$i){
$sql[$x].=",'".mysqli_real_escape_string($con,$emapData[$i])."'";
}
$sql[$x].=",'".mysqli_real_escape_string($con,$inverter)."');"; // end first query of pair
$sql[$x].="$data_sql,'".mysqli_real_escape_string($con,$emapData[26])."','".mysqli_real_escape_string($con,$inverter)."')"; // whole second query of pair
fclose($file);
}
// run all queries
if(mysqli_multi_query($con,implode(';',$sql)){
do{
$tally+=mysqli_affected_rows($con);
} while(mysqli_more_results($con) && mysqli_next_result($con));
}
// assess the outcome
if($error_mess=mysqli_error($con)){
echo "<script type=\"text/javascript\">alert(\"Syntax Error: $error_mess\");</script>";
}elseif($tally!=$x*2){ // I don't expect this to be true for your case
echo "<script type=\"text/javascript\">alert(\"Logic Error: Only $tally row",($tally!=1?"s":"")," inserted\");</script>";
}else{
echo "<script type=\"text/javascript\">alert(\"CSV File has been successfully Imported.\"); window.location = \"four.php\"/</script>";
}
mysqli_close($con);

If INSERT IGNORE echo "Query was ignored"? (mysql/php)

I have a query like this:
$query="INSERT IGNORE INTO mytable (key, word1, word2) VALUES (1, 'abc', 'def')";
And I'd like to somehow "catch" if the query was ignored because the primary key already exists.
Is there any was to make an "if" statement so my program could notify the user that the query was ignored?
I solved it by using mysql_affected_rows to check if no rows were affected by the query.
if($productquery&&mysql_affected_rows($conn)>0){
echo "Success.";
echo mysql_affected_rows($conn); //returns 1
}else{
echo "Some error." . mysql_error(). " ".mysql_affected_rows($conn); //returns 0 affected rows since it was ignored
}
The problem is when you especially ignore the errors then you don't get them. So you have to remove the IGNORE and catch the error instead.
You don't get any errors in your case.

update mysql database using php

I'm trying to update my users table using php.
$update_query="
UPDATE `users` SET `name`='$addname',
`lastname`='$addlastname',
`password`='$addpsswrd',
`email`='$addemail'
where `username`='$modifyusername'
";
echo $update_query;
if( mysql_query($update_query) or die('Erreur SQL !'.$req.'<br>'.mysql_error()))
echo "Lignes modifiées : ", mysql_affected_rows();
But I always get :
UPDATE `users` SET `name`='Jolia ',`lastname`='roberta', `password`='password1234',`email`='roberta.joli#hotmail.fr' where `username`='user11'
Lignes modifiées : 0
How can I fix this? the user11 exist in my database and I tried to copy past this query as it is in the output echo message I get 0 modified line so how can I fixed on the php part?
When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.
http://us1.php.net/manual/en/function.mysql-affected-rows.php
I am not sure , but my suggestion is try to remove the single quotation marks ['] from the column name. ps: this is my first time answer question on stackoverflow
like
$update_query="
UPDATE users SET name='$addname',
lastname='$addlastname',
password='$addpsswrd',
email='$addemail'
where username='$modifyusername'
";
echo $update_query;
if( mysql_query($update_query) or die('Erreur SQL !'.$req.'<br>'.mysql_error()))
echo "Lignes modifiées : ", mysql_affected_rows();

mysql_query works but error check returns an error

This code works and enters all of the correct information into the database but the error check returns an error. I could remove the error check but I'm afraid of creating some nightmare that comes back to haunt me later or that I'm missing a fundamental issue:
$sql5a = mysql_query("SELECT id FROM categories WHERE category='$category'");
$categoryresult = mysql_fetch_array($sql5a);
$oldcategoryid = $categoryresult['id'];
$sql6a = "INSERT INTO lookupcategory SET
fbid='$fbid2',
categoryid='$oldcategoryid'";
if ( #mysql_query($sql5b) ) {
echo('sql5b updated successfully<br>');
} else {
echo('Error: sql5b not updated<br>'.mysql_error() );
}
if ( #mysql_query($sql6b) ) {
echo('sql6b updated successfully<br>');
} else {
echo('Error: sql6b not updated<br>'.mysql_error() );
}
The output is: "Error: sql5b not updated
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 'Resource id #7' at line 1"
"sql6b updated successfully"
When I check the database all entries are correct. If sql5a didn't work, sql6b couldn't work, hence my confusion over the error.
A sample Category would be: Travel/Leisure
The category was originally created from a form response:
$category = htmlentities($fbdetail['category'], ENT_QUOTES);
and entered into the database successfully. An id number was assigned using AUTO_INCREMENT.
You assign query to variable $sql5a, but call #mysql_query($sql5b).
$sql5b doesn't exist (at least in this sample). Same with $sql6a...
You can use INSERT syntax without VALUES, but you need to ommit INTO keyword.
$sql5a = mysql_query("SELECT id FROM categories WHERE category='$category'");
if ( $res5a = #mysql_query($sql5a) ) { // first execute query and store resource in variable
echo('sql5a selected successfully<br>');
} else {
echo('Error: sql5a failed<br>'.mysql_error() );
}
$categoryresult = mysql_fetch_array($res5a); // fetch array passing the RESOURCE var, NOT query string
$oldcategoryid = $categoryresult['id'];
$sql6a = "INSERT lookupcategory SET
fbid='$fbid2',
categoryid='$oldcategoryid'";
if ( #mysql_query($sql6a) ) {
echo('sql6a inserted successfully<br>');
} else {
echo('Error: sql6a failed<br>'.mysql_error() );
}
I don't know where you get $fbid2 or $category from, since it's not in this piece of code.
The syntax for the insert is :
INSERT INTO table(col1, col2 ...) VALUES(val1, val2 ...)
In your specific case:
$sql6a = "INSERT INTO table(fbid, categoryid) VALUES('{$fbid2}','{$oldcategoryid}')"

Categories