Page 1 of 1

check if data exists

Posted: Fri Sep 02, 2005 11:18 am
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?

Re: check if data exists

Posted: Fri Sep 02, 2005 11:23 am
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.

Posted: Fri Sep 02, 2005 11:24 am
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()

Posted: Fri Sep 02, 2005 11:30 am
by feyd
tip: watch out for SQL injection. :) (look in the security board for a long thread about it)