mysql Duplicate error handling - php

I'm trying to use PHP to enter data from a form. When I try to enter duplicate data a bad message pops like
Something went wrong with this:
INSERT INTO customer VALUES('jamie9422','Jamie Lannister','sept of baelor','jamie#cersei.com',9422222222,0) Duplicate entry 'jamie9422' for key 'PRIMARY' "
Instead, I want to display a clean error message. How can I do that. Here's my code I've written so far...
<?php
include_once "dbConnect.php";
$connection=connectDB();
if(!$connection)
{
die("Couldn't connect to the database");
}
$tempEmail = strpos("{$_POST["email"]}","#");
$customer_id=substr("{$_POST["email"]}",0,$tempEmail).substr("{$_POST["phone"]}",0,4);
//$result=mysqli_query($connection,"select customer_id from customer where customer_id='$customer_id' ");
//echo "customer_id is".$result;
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( mysql_query($query)) {
echo "It seems that user is already registered";
} else {
$command = "INSERT INTO customer VALUES('{$customer_id}','{$_POST["name"]}','{$_POST["address"]}','{$_POST["email"]}',{$_POST["phone"]},0)";
$res =$connection->query($command);
if(!$res){
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
echo "Welcome ".$_POST["name"]." \nCongratulations on successful Registration. Refill your Wallet here";
//$cutomerRetrival = mysql_query("select from customer where customer_id='$customer_id'");
echo "<br>Please note your customer ID :".$customer_id;
}
/*if($result)
{
echo "Query Fired";
$dupentry = mysqli_num_rows($result);
if($dupentry==1)
{
echo "You are already Registered";
exit;
}
}*/
?>

The error code (number) is 1022.
You can e.g. define a constant for that (so that somebody else in x months has a chance to understand the code) like
define('ER_DUP_KEY', 1022);
and then do something like
if(!$res){
if ( <error code>==ER_DUP_KEY ) {
handleDuplicateEntryError();
}
else {
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
}
since I don't know how $res =$connection->query($command); works (and what $connection is I can't tell you exactly how to implement <error code>==ER_DUP_KEY, could be by using mysql_errno.
But it seems to be somehow intermingled with mysql_query($query), i.e. the old, deprecated mysql_* extension and some custom class. You might want to fix that first.... ;-)
see http://docs.php.net/manual/en/mysqlinfo.api.choosing.php

Your code doesn't check for existing record properly
Change
if (mysql_query($query)) {
echo "It seems that user is already registered";
}
to
$result = mysql_query($query);
if (mysql_num_rows($result)) {
echo "It seems that user is already registered";
}
Also, PLEASE do not use $_POST variables without escaping them first, use something like mysql_real_escape_string() to escape each variable passed from the user, otherwise your website will be hacked really fast with SQL Injection.

Make some update into your and then try to get error message 'customer already registered.'
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$res= mysql_query($query);
$customer_count = mysql_num_rows($res);
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( $customer_count > 0 ) {
echo "It seems that user is already registered";
} else {
...................................

Thank you all.
Actually I was using mysqli API in my connectDB.php file..
Hence I needed to call functions on mysqli.
Instead I was calling mysql. i.e I was creating a new connection, thus the query wasn't getting fired at all.
Changed to mysqli->query($result) that is object oriented style
and it worked fine....

Use Try Catch instead.
try{
$res =$connection->query($command);
}catch(Exception $e){
die( "Write your error appropriate message here");
}

Related

PHP try/catch with SQL. All or Nothing

I need to make changes in two databases at the same time, but I don't want either of them to go through if either fails.
This block of code attempts to update the password for a user in two separate databases. The first query goes, then the database is switched, then the second query goes. The try/catch block will fire if there is an error, however if the first query is successful and the second query is not, the first query still goes through despite the exception being thrown and caught. Is try/catch not the right way to approach this?
Thanks for any input!
try {
$new_hash = password_encrypt($new_password);
$query = "UPDATE user SET ";
$query .= "user.hashedPassword = '{$new_hash}' ";
$query .= "WHERE user.userID = '{$user_id}' ";
if(!mysqli_query($connection, $query)) {
throw new Exception('Change Unsuccessful.');
}
if(!mysqli_select_db($connection, 'sub_' . $user['username'] . '_db')) {
throw new Exception('Change Unsuccessful. Switch Error.');
}
$query = "UPDATE user SET ";
$query .= "user.hashedPassword = '{$new_hash}' ";
$query .= "WHERE user.userID = '{$user_id}' ";
if(!mysqli_query($connection, $query)) {
throw new Exception('Change Unsuccessful.');
}
$_SESSION['message'] = 'Password Changed.';
$_SESSION['messageType'] = 'success';
redirect_to("/main.php");
} catch(Exception $e) {
$_SESSION['message'] = $e->getMessage();
$_SESSION['messageType'] = 'danger';
redirect_to("/main.php");
}
I know this is old, but I came across it via a DuckDuckGo search first. Here is what I think to be the right answer;
Use SQL transactions.
In your case, you must start the transactions for both databases, and if either database throws an exception, roll them both back.
At the end of the day, transaction allows you to actually try and complete or undo the command.
you can try to add
if (!$mysqli->query("query"))
{
printf("Error: %s\n", $mysqli->error);
}
and see if there's any error

PHP and MySQL insert successful but can't see that the row has been inserted in PHPMyAdmin

I have a simple registration form that inserts data into MySQL table. I am checking for error as well but it results in SUCCESS echo.
On Stackoverflow, I looked for the question, but couldn't really find an answer pertaining to my situation. Please forgive me if it has been answered. If it has been answered already, please provide a link and I will apologize for wasting anybody's time. Thank you! Below is my code:
<?php
if($_GET["regname"] && $_GET["regpass1"] && $_GET["regpass2"])
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$servername="localhost";
$username="root";
$password='';
$conn= mysql_connect($servername,$username,$password)or die(mysql_error());
mysql_select_db("test")or die("cannot select DB");
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
if($sql)
{
echo "Success";
}
else
{
echo "Error";
}
print "<h1>you have registered sucessfully</h1>";
print "<a href='main_login.php'>go to login page</a>";
}
else print "passwords doesnt match";
}
else print"invaild data";
?>
You are checking if $sql exists. $sql is your actual query string. In this case, of course it will show it exists. Secondly, please do not use mysql_* for new code as it is deprecated. Instead use mysqli_* or PDO.
You actually haven't executed your query in your code. (Using deprecated mysql_* which is ill advised) the code as follows should execute the query:
$result = mysql_query($sql, $conn);
if($result == true)
echo 'Success';
else
echo 'Failure';
Instead of using the code above, I would strongly recommend updating your current code to use mysqli_* or PDO forms. You can read up more on this topic at the manpages linked previously.
Look at these lines:
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
if($sql)
{
echo "Success";
}
You have created a request in $sql variable but have not executed it. The variable itself is non-empty, non-false so it evaluates to TRUE in the if-condition.
You should do it like this:
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
$result = mysql_query($sql);
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
else
{
echo "Success";
}
Just to be on the safe side I'll note that using variables from $_GET request like this, unfiltered, is an inapprorpiate tactic as it will lead to SQL injections, but I suppose you simplified code sample for the sake of brevity.

mySQLi_affected_rows check not working, or is it...?

(Sorry, I don't really know what I am doing.)
I have this Unity game in an iframe on Facebook calling a php file in the same directory, and that much is working. What I want it to do is update the player record if it is there and make one if it isn't.
This script runs but it always returns a "not here" and when I check the database, it is in fact creating the records each time, identical but for the datetime field. So I don't understand why affected_rows is never coming back as "1".
<?php
$db = #new mysqli('••.•••.•••.••', '•••••••••••', '••••••••','•••••••••••');
if ($db->connect_errno)
{
echo("Connect failed "+mysqli_connect_error());
exit();
}
$inIP = $_POST["ip"];
$playerIP = mysqli_real_escape_string($db, $inIP);
$inUN = $_POST["un"];
$playerUN = mysqli_real_escape_string($db, $inUN);
$query = "UPDATE lobby SET whens=NOW(), wherefores='$playerIP', whys=0 WHERE whos='$playerUN'";
mysqli_query($db, $query);
if (mysqli_affected_rows($db) > 0)
{
echo "here";
}
else
{
$query2 = "INSERT INTO lobby (whens,whos,wherefores,whys) values (NOW(),'$playerUN','$playerIP',0)";
mysqli_query($db, $query2);
echo "not here";
}
if ($db)
{
$db->close();
}
?>
You have a typo:
wherefores=$playerip
it should be
wherefores=$playerIP
because of that
mysqli_affected_rows($db)
returns
-1
Sounds like you're experiencing the same problem as me, especially if you are running your code through a debugger. I've investigated the issue with Netbeans and Xdebug and it seems this is a bug in the MySQLi extension itself. An according bug report has been made. In the meantime you can instead use another expression, e.g.:
if (mysqli_sqlstate($dbc) == 00000) {
//your code
}
to continue debugging your remaining code.

mysql_query with PHP variables

This should be easy but I'm can't make it work.
The idea is to look for an email adress posted from a form. If it exists echo something and if not echo something else.
My code is:
<?php
//MySQL Database Connect
mysql_connect("localhost", "********", "**********")
or die("Unable to connect to MySQL");
//get data from form
$email=$_POST['email'];
//ask the database for coincidences
$result = mysql_query("SELECT email FROM pressmails WHERE email='.$email.'");
$num_rows = mysql_num_rows($result);
if($num_rows < 0){
echo "The user is registered";
} else {
echo "The user is not registered";
}
//Close database connection
mysql_close();
?>
You are not concatenating string properly.
$result = mysql_query("SELECT email FROM pressmails WHERE email='.$email.'");
should be
$result = mysql_query("SELECT email FROM pressmails WHERE email='".$email."'");
You should end the string by using a closing quote (if you started the string with " you must end the string with " too, same for ').
And do not forget to use mysql_real_escape_string, otherwise the script is not safe.
The script will become something like this:
// save the query in a variable, so we can echo it to debug when it doesn't work as expected
$sql = "SELECT email FROM pressmails WHERE email='".mysql_real_escape_string($email)."'";
$result = mysql_query($sql);
You do not need the concatenation identifiers, since wrapping a literal in " will automatically parse variables into the string:
$result = mysql_query("SELECT email FROM pressmails WHERE email='$email'");
You should watch out, mind you. Doing the above represents a significant SQL injection vulnerability. You should consider sanitizing $email as a minimum. Also see my comment about the mysql_* functions in PHP.
From the Docs:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_close() PDO: Assign the value of NULL to the PDO object
(assuming you get your syntax errors corrected) isn't the logic of this backwards?
if($num_rows < 0){
echo "The user is registered";
} else {
echo "The user is not registered";
}
if the user is registered their email is in the database and the query returns one or more rows
try
if($num_rows){
echo "The user is registered";
} else {
echo "The user is not registered";
}

Duplicate check before adding into database

I have a code which kinda works, but not really i can't figure out why, what im trying to do is check inside the database if the URL is already there, if it is let the user know, if its not the go ahead and add it.
The code also makes sure that the field is not empty. However it seems like it checks to see if the url is already there, but if its not adding to the database anymore. Also the duplicate check seems like sometimes it works sometimes it doesn't so its kinda buggy. Any pointers would be great. Thank you.
if(isset($_GET['site_url']) ){
$url= $_GET['site_url'];
$dupe = mysql_query("SELECT * FROM $tbl_name WHERE URL='$url'");
$num_rows = mysql_num_rows($dupe);
if ($num_rows) {
echo 'Error! Already on our database!';
}
else {
$insertSite_sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
echo $url;
echo ' added to the database!';
}
}
else {
echo 'Error! Please fill all fileds!';
}
Instead of checking on the PHP side, you should make the field in MySQL UNIQUE. This way there is uniqueness checking on the database level (which will probably be much more efficient).
ALTER TABLE tbl ADD UNIQUE(URL);
Take note here that when a duplicate is INSERTed MySQL will complain. You should listen for errors returned by MySQL. With your current functions you should check if mysql_query() returns false and examine mysql_error(). However, you should really be using PDO. That way you can do:
try {
$db = new PDO('mysql:host=localhost;db=dbname', $user, $pass);
$stmt = $db->query('INSERT INTO tbl (URL) VALUES (:url)');
$stmt->execute(array(':url' => $url));
} catch (PDOException $e) {
if($e->getCode() == 1169) { //This is the code for a duplicate
// Handle duplicate
echo 'Error! Already in our database!';
}
}
Also, it is very important that you have a PRIMARY KEY in your table. You should really add one. There are a lot of reasons for it. You could do that with:
ALTER TABLE tbl ADD Id INT;
ALTER TABLE tbl ADD PRIMARY KEY(Id);
You should take PhpMyCoder's advice on the UNIQUE field type.
Also, you're not printing any errors.
Make sure you have or die (mysql_error()); at the end of your mysql_* function(s) to print errors.
You also shouldn't even be using mysql_* functions. Take a look at PDO or MySQLi instead.
You're also not executing the insert query...
Try this code:
if(isset($_GET['site_url']) ){
$url= $_GET['site_url'];
$dupe = mysql_query("SELECT * FROM $tbl_name WHERE URL='$url'") or die (mysql_error());
$num_rows = mysql_num_rows($dupe);
if ($num_rows > 0) {
echo 'Error! Already on our database!';
}
else {
$insertSite_sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
mysql_query($insertSite_sql) or die (mysql_error());
echo $url;
echo ' added to the database!';
}
}
else {
echo 'Error! Please fill all fileds!';
}
As PhpMyCoder said, you should add a unique index to the table.
To add to his answer, here is how you can do what you want to do with only one query.
After you add the unique index, if you try to "INSERT INTO" and it result in a duplicate, MySQL will produce an error.
You can use mysql_errno() to find out if there was a duplicate entry and tell the user.
e.g.
$sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
$result = mysql_query($sql);
if($result === false) {
if(mysql_errno() == $duplicate_key_error) {
echo 'Error! Already in our database!';
} else {
echo 'An error has occurred. MySQL said: ' . mysql_error();
}
}
mysql_error() will return the mysql error in plain english.
mysql_errno() returns just the numeric error code. So set $duplicate_key_error to whatever the code is (I don't know it off the top of my head) and you are all set.
Also note that you don't want to print any specific system errors to users in production. You don't want hackers to get all kinds of information about your server. You would only be printing MySQL errors in testing or in non-public programs.
ALSO! Important, the mysql functions are deprecated. If you go to any of their pages ( e.g. http://php.net/manual/en/function.mysql-errno.php) you will see recommendations for better alternatives. You would probably want to use PDO.
Anyone who wants to edit my answer to change mysql to PDO or add the PDO version, go ahead.

Categories