Page 1 of 1

Why is this an invalid query?

Posted: Wed Dec 08, 2004 11:25 pm
by Seona
Hi guys,

I'm a complete newcommer to PHP and am trying to teach myself as I go. I've looked through lots and lots of online resources, and now have some stuff that works in principal but is dying on me when I try and modify it for my own use. I have the following code:

Code: Select all

<?php
	/* declare some relevant variables  */
	$DBhost = "localhost";
	$DBuser = "username";
	$DBpass = "password";
	$DBName = "thisDB";
	$table = "user";

	import_request_variables('p', 'p_');

	$link = mysql_connect($DBhost,$DBuser,$DBpass);
	@mysql_select_db("$DBName") or die("Unable to select database $DBName"); 

	$sqlquery = "SELECT * FROM $table WHERE username = $p_username AND password = $p_password";

	echo $sqlquery . "<br />";

	$result = mysql_query($sqlquery,$link);
	if (!$result = mysql_query($sqlquery,$link))
    	     exit("Illegal query");

	$number = mysql_num_rows($result);
	echo "num rows = " . $number;
?>
I'm trying to compare the values in the database with what the user has entered into the login form. If I remove the two clauses from the query (no WHERE or AND) it all works fine. The last line says
num rows = 2
which is correct since there are currently two test records in the database.

I'm outputting the query for bugtesting, and it's appearing just fine:
SELECT * FROM user WHERE username = admin AND password = france
Yet for some reason it's still coming up as an error. :(

Can someone please tell me what I'm doing wrong?

Thanks.

Seona.

Posted: Thu Dec 09, 2004 12:05 am
by rks
Try wrapping your username and password data in single quotes:

Code: Select all

$sqlquery = "SELECT * FROM $table WHERE username = '$p_username' AND password = '$p_password'";

Posted: Thu Dec 09, 2004 12:07 am
by Benjamin
Hi...

When you have an sql query, you must wrap the query data in single qoutes. Select * from TableName where TableColumn='data'

I rewrote your code.

Code: Select all

<?php
/* declare some relevant variables  */
$DBhost = "localhost";
$DBuser = "username";
$DBpass = "password";
$DBName = "thisDB";
$table = "user";

import_request_variables('p', 'p_');

$link = mysql_connect($DBhost,$DBuser,$DBpass);
@mysql_select_db("$DBName") or die("Unable to select database $DBName");

$sqlquery = "SELECT * FROM $table WHERE username='" . $p_username . "' AND password='" . $p_password . "'";

echo $sqlquery . "<br />";
$result = mysql_query($sqlquery,$link);

if (!$result = mysql_query($sqlquery,$link)) exit("Illegal query");

$number = mysql_num_rows($result);
echo "num rows = " . $number;

?>

Posted: Thu Dec 09, 2004 12:19 am
by Seona
Oh yeah... That's right! I'd forgotten that bit. *sheepish grin*

Thanks. :)