Jump to content

[SOLVED] check to see if entry exists...


blurrydude

Recommended Posts

I've tried to search for this...

I just want to make sure that no one has the same username as someone already in the table. I've even tried implementing IF EXISTS statements in the query.

 

<?
session_start();
include('db.php');

$username=$_POST['username'];

$query = mysql_query("SELECT * FROM members WHERE username = ". $username .";");

if($query)
{
echo "User ". $username ." already exists, please try another.";
}
else
{
echo "This username is available.";
}
echo "<br><br>". $query ."<br><br>";//to see what the script sees as I edit.
?>
<form action="checkname.php" method="POST">
<input type="text" name="username"><br>
<input type="submit">
</form>

Link to comment
https://forums.phpfreaks.com/topic/101148-solved-check-to-see-if-entry-exists/
Share on other sites

Strings in MySQL queries must be quoted..

 

Also, why are you selecting * (all rows) when you really don't need them? Wasting memory :)

 

$query = mysql_query("SELECT `username` FROM `members` WHERE `username` = '". $username ."';");

 

Dont forget to sanitize user input ;)

ok, now code looks like this, I used ID as the single field to select:

<?
session_start();
include('db.php');

$username=$_POST['username'];

$query = mysql_query("SELECT `ID` FROM `members` WHERE `username` = '". $username ."';");

if($query)
{
echo "User ". $username ." already exists, please try another.";
}
else
{
echo "This username is available.";
}
echo "<br><br>". $query ."<br><br>";//to see what the script sees as I edit.
?>
<form action="checkname.php" method="POST">
<input type="text" name="username"><br>
<input type="submit">
</form>

 

No matter what I type into the form, I get Resource id #3 from the echo $query.

<?
session_start();
include('db.php');

$username=$_POST['username'];

$query = mysql_query("SELECT `ID` FROM `members` WHERE `username` = '". $username ."';");
$queryresult = mysql_fetch_row($query);

if($queryresult)
{
echo "User ". $username ." already exists, please try another.";
}
else
{
echo "This username is available.";
}

mysql_close($link);

?>
<form action="checkname.php" method="POST">
<input type="text" name="username"><br>
<input type="submit">
</form>

 

Final code, works great, thanks for the help.

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.