check if data exists

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

check if data exists

Post by SidewinderX »

im trying to write a code that connects to my database and checks to see if a value exists. it it does it will display "Player already exists." If it does not exist it will it will display "Player does not exist."

here is my code

Code: Select all

$pid = "10864580281";
$db = mysql_connect($dbhost, $dbuname, $dbpass);
mysql_select_db($dbname, $db);
$result = mysql_query("SELECT * FROM stats WHERE pid=$pid", $db);

while ($row = mysql_fetch_assoc($result)){

if ($pid) {
  echo "Player already exists";
}
else 
{
  echo "Player does not exist";
}

}
for testing perposes im using a static pid rather then a pid that is submited from a form.

my code kind of works...if the pid exists it does display "Player already exists" however if it does not exist, it dosnt display anything, could someone help me as to where i am going wrong?
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Re: check if data exists

Post by nielsene »

Code: Select all

$pid = "10864580281";
$db = mysql_connect($dbhost, $dbuname, $dbpass);
mysql_select_db($dbname, $db);
$result = mysql_query("SELECT * FROM stats WHERE pid=$pid", $db);

while ($row = mysql_fetch_assoc($result)){

if ($row['pid]') { // <-------------------
  echo "Player already exists";
}
else 
{
  echo "Player does not exist";
}

}
Would be the easiest fix, that also illustrates why it was broken. Notice that you weren't checking the results of the query.

However, a better approach would probably to check mysql_num_rows() for 0 or 1, instead of the contents of the row.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

$pid = "10864580281";
$db = mysql_connect($dbhost, $dbuname, $dbpass);
mysql_select_db($dbname, $db);
$result = mysql_query("SELECT * FROM stats WHERE pid=$pid", $db);

if (mysql_num_rows($result) > 0) {
  echo "Player already exists";
}
else
{
  echo "Player does not exist";
}
mysql_num_rows()
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

tip: watch out for SQL injection. :) (look in the security board for a long thread about it)
Post Reply