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
https://forums.phpfreaks.com/topic/199456-how-to-deal-with-mysql-messages/
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);
}

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.