Page 1 of 1

Database lookup

Posted: Mon Mar 14, 2011 11:24 am
by infrabyte
Hi,

I have a database with a couple of tables in it and I am posting data into the filed successfully. After that is done I want to take an entry that a user has posted and compare it to a table called 'codes' of entries (under field 'barcodes') and return the result. (this is for a competition I am running). Here is the second part of my code:

$sel=mysql_query("select * from codes");
while($log=mysql_fetch_array($sel))
{
if($_POST['barcode']==$log['barcode'])
{
echo"CONGRATULATIONS...You have won!";
}
else
{
echo"Sorry, try again";
}
}

This works but filters through all the results in the database and gives me...

CONGRATULATIONS...You have won!Sorry, try againSorry, try again....etc

I only want one result if the person won or not...I cant seem to pinpoint the error...

Please help...thank you

Re: Database lookup

Posted: Mon Mar 14, 2011 11:30 am
by danwguy
You should search specifically for that record, something like...

Code: Select all

$sel = mysql_query("SELECT * from codes where barcode="' . $_POST['barcode'] . '");
then just check the number of rows it returned. if it's 1 then they win, if it's 0 then sorry try again.

Re: Database lookup

Posted: Mon Mar 14, 2011 11:35 am
by infrabyte
there seems to be an " missing there somewhere...it breaks the code

Re: Database lookup

Posted: Mon Mar 14, 2011 11:41 am
by danwguy
Sorry it's still early in the morning, you should save the post value first, then run your query...

Code: Select all

$barcode = $_POST['barcode'];
$sel = mysql_query("SELECT * from codes WHERE barcode=$barcode") or die("Could not SELECT: " .mysql_error());
$num = mysql_num_rows($sel);
if($num >= 1) {
echo "You win";
}
if($num == 0) {
echo "Sorry try again";
}

Re: Database lookup

Posted: Mon Mar 14, 2011 11:59 am
by infrabyte
AWESOME...you're a star...

That works gr8

Thank you very much

Re: Database lookup

Posted: Tue Mar 15, 2011 2:09 am
by infrabyte
Hi...

Ok I thought that worked but obviously not...I get this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Not sure where the error is.

Thanx

Re: Database lookup

Posted: Tue Mar 15, 2011 2:19 am
by infrabyte
Ok I found the error...
in the line - $sel = mysql_query("SELECT * from codes WHERE barcode=$barcode") or die("Could not SELECT: " .mysql_error());

it should have $barcode in single quotes ' ' as follows:

$sel = mysql_query("SELECT * from codes WHERE barcode='$barcode'") or die("Could not SELECT: " .mysql_error());

thanx for all your help