Jump to content

[SOLVED] Unique MYSQL Column, how to return errors to PHP?


nafetski

Recommended Posts

Hello everyone =)  Still fairly new to PHP/MySQL - but getting the basics down.  I'm writing a login script (I know, tons of these out there) but I need one that is just a little bit more complex than your basic one.

 

Right now I am creating a utility to allow an admin to add new users to our system.  Right now the table has just two columns...one username, one pass.  I have set username as primary key (so I won't have duplicates) and it's working great.

 

The only thing is..how do I output an error if that username already exists?  Right now the script runs through, says the user was added - (but it wasn't).  How can PHP detect if the data was really inserted or not? 

 

Sorry if this has been asked before, I've tried googling for an hour and maybe I'm just nto putting in the right search terms.  Thanks!

Link to comment
Share on other sites

I don't really understand your question, but I think you bundled two questions into one.

 

1) How to check if a user already exists?

<?php
$query = mysql_query("SELECT COUNT(*) FROM Members WHERE username = '" . $username . "'");
$rows = mysql_num_rows($query);

if ($rows <= 0) echo 'No such user';
else echo 'Such a user exists';
?>

 

2) How to detect if the query was successful or not?

PHP automatically return a false if the query fails.

<?php
$query = @mysql_query("INSERT INTO Members (`username`,`password`) VALUES ('"  . $username . "', '" . $password . "')");

if ($query != false) echo 'Query executed successfully';
else echo 'Query has failed';
?>

Note the at sign (@) in front of the function, it is to force the script not to output an error if the function produces an error.

 

Hope it helps.

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.