By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,117 Members | 1,714 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,117 IT Pros & Developers. It's quick & easy.

Checking if record with some field exists

P: n/a
Hello,

I am new to PHP so I have done a research on how to check if an entry
exists on the table. I came up with the following code:

include("dbinfo.inc.php");
$Name=$_POST['Name'];
$Code=$_POST['Code'];
mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT * FROM Contacts WHERE Code=$Code");
if($row = mysql_fetch_array($result)) echo "exists";
else
{$query = "INSERT INTO Contacts VALUES ('','$Name','$Code')";
echo "ok";}
mysql_query($query);
mysql_close();

This works if the code is integer (1264), however if the code is
string (a4fg5h4) it shows - "Warning: mysql_fetch_array(): supplied
argument is not a valid MySQL result resource in D:\xampp\htdocs\reg
\insert.php on line 10
ok"

I can't found out what is the problem here as all the examples on the
web shows similar codes to do checking.
Regards,
K. Vijayakumar

May 30 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Edwina Rothschild wrote:
Hello,

I am new to PHP so I have done a research on how to check if an entry
exists on the table. I came up with the following code:

include("dbinfo.inc.php");
$Name=$_POST['Name'];
$Code=$_POST['Code'];
mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT * FROM Contacts WHERE Code=$Code");
if($row = mysql_fetch_array($result)) echo "exists";
else
{$query = "INSERT INTO Contacts VALUES ('','$Name','$Code')";
echo "ok";}
mysql_query($query);
mysql_close();

This works if the code is integer (1264), however if the code is
string (a4fg5h4) it shows - "Warning: mysql_fetch_array(): supplied
argument is not a valid MySQL result resource in D:\xampp\htdocs\reg
\insert.php on line 10
ok"

I can't found out what is the problem here as all the examples on the
web shows similar codes to do checking.
Regards,
K. Vijayakumar
Your mysql_query failed.

You should always check the result of any MySQL call (except
mysql_close(), maybe).

$result = mysql_query("SELECT * FROM Contacts WHERE Code=$Code");
if (!$result)
echo "Query failed!" . mysql_error();
else
if($row = mysql_fetch_array($result)) echo "exists";
...

or,
if (mysql_num_rows($result) 0) echo "exists";

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
May 31 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.