Jump to content

How to deal with mySql messages ?


Rommeo

Recommended Posts

i have a table like :

 

id-username

1  newbie

 

id = primary key

username = unique

 

For example;

when i try to be member with the username "newbie", mysql gives me an error like "Duplicate entry 'newbie' for key 'username' ". what i want to do is : i dont want this mysql error to see.i want to write a function that understands the error message so that i can print a warning like "this username is in use, please use another ".

 

but how will my function understand the error type ?

 

i m using a query like :

<?php
@mysql_query("INSERT INTO user 	( id, username.. ) VALUES 	( ... ) || die ( mysql_error() );
}
?>

Link to comment
Share on other sites

YOU  need to check for that error condition BEFORE you do the insert.

 

$query = "SELECT username FROM table WHERE username='$username'";
$result = mysql_query($query);

if(mysql_num_rows($result)>0)
{
    echo "The username '{$username}' is already in use.";
}
else
{
    $query = "INSERT INTO table (username) VALUES ('{$username}')";
    $result = mysql_query($query);
}

Link to comment
Share on other sites

Was typing this while mjdamato posted. Basically the same thing.

 

You'll need to use a select statement to check if the username is in use first before attempting to insert it into the database.

 

So use:

 

mysql_query("SELECT username FROM users WHERE username='".$username."'");

 

If the query returns more than 0 rows, that username is taken. If not continue inserting the values into the database.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.