Custom SQL errors...

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
cgroup
Forum Newbie
Posts: 13
Joined: Tue Jun 03, 2003 11:51 pm
Location: PA

Custom SQL errors...

Post by cgroup »

I can't seem to find a way to create a custom error. I want to have the script tell a user that a username is already taken. Rather than output 'duplicate entry for key 2' it could say 'sorry, that username is already registered'.

I tried using the die() function but it didn't seem to fix the problem.

PHPMyAdmin has a nice error handling where it'll say 'MySQL Said:' followed by the error. I tried tracking that down in their code but it's a big script.

Anyone know how to do this?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

have you tried to exit function?

Is this what you want?

Code: Select all

<?
$username = "Johnny";
$username2 = "Tommy"; // these are nothing I don't know how you are gathering your input, so I'm just doing it as simple as possible.

if ($username != $username2){

//whatever you want to do

}elseif{

exit("Username Already Exists.");

}?>
Check out http://ca2.php.net/exit for more information. This isn't really the proper use of the exit function :s but I hope it gets the idea across. The good thing about using exit is that it terminates the script from going any furthur, which is usefull for protecting against running parts of the script people arn't supposed to.
cgroup
Forum Newbie
Posts: 13
Joined: Tue Jun 03, 2003 11:51 pm
Location: PA

Post by cgroup »

Ok - I figured it out. The problem was that the script I'm using has the database connect code in another script. I had to go in there and change the 'or die(mysql_error())' to 'or die(sql_error))'.

I then put this code at the top of the connect file:

Code: Select all

function sql_error() &#123;
  $sql_err_no = mysql_errno();
 if ($sql_err_no = 1062) &#123;
	 $fin_error = "The username is already taken";
 &#125; else &#123;
	 $fin_error = mysql_error();
 &#125;
  return "$fin_error";
&#125;
Post Reply