Reply to Re: checking if record with some field exists

Your name:

Reply:


Posted by Mike P2 on 05/18/07 19:41

On May 18, 2:30 pm, mookid <raimundas.ju...@gmail.com> 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.

In SQL, strings need to be quoted. That example puts $Code right into
the query without putting the code in quotes (use single-quotes).
Change the end of the query to:
WHERE Code='$Code'

I hope you realize that code is not production-quality. It is insecure/
breakable, $Code and $Name need to be escaped. You should replace the
second and third lines with something like:

$Name = isset( $_POST['Name'] )
? mysql_real_escape_string( $_POST['Name'] )
: '';
$Code = isset( $_POST['Code'] )
? mysql_real_escape_string( $_POST['Name'] )
: '';

-Mike PII

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация