views:

51

answers:

3

Hi there,

I have a problem in sql query execution.I am using this sql query:

$userid = 1;  

$sql = mysql_query("
  SELECT ID, Nm, Address, date_format(DateOfBirth, '%d%M%Y') as DateOfBirth 
  FROM PersonalDetails where UserMasterID = $userid
") or die (mysql_error());

The result appears as:

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

When I execute this in PHPMyAdmin it works properly. I am using mysql(5.0.5b) and PHP (5.2.6)

Can you help me please?

+5  A: 

If UserMasterID is not an integer, you may need to put quotes around the value:

PersonalDetails where UserMasterID = '$userid'"

The query you are quoting above is not identical to what you run in phpMyAdmin. It contains a PHP variable. When in SQL trouble, always output and analyze the parsed query (with no references to PHP variables in them).

$query = "select ID... etc. etc.";
$result = mysql_query($query);

if (!$result) 
 echo "Error in query $query: ".mysql_error();

90% of problems can be spotted and solved that way.

Pekka
you forgot to add a query itself to the debug message :) and you may notice from my posts that I popularize trigger_error usage over echo. You may find it extremely useful.
Col. Shrapnel
@Col yup, I like `trigger_error` too, good point. But `$query` is in there, isn't it? Or am I overlooking something?
Pekka
I run query in phpmyadmin by passing 1 to usermasterid and not php variable, my friend.
Rishi2686
@Rishi can you show the parsed query? Can you replace `AS DateOfBirth` by `AS DateOfBirth2? (Although if it's that, it shouldn't work in PHPMyAdmin either.)
Pekka
@Pekka Finally I could get it. The sql query was creating problem when I was passing $userid, instead I tried to pass $_GET['q'], the value I was getting from url, and hurrrray!! it worked, thank you man, for hint.
Rishi2686
A: 

If it runs correctly in PHPMyAdmin, but not in the PHP code, then that says to me that PHPMyAdmin is performing it's famous task of escaping and sanitizing everything it possibly can.

Change your code to this and check it.

$userid = 1;  

$sql = mysql_query("
  SELECT `ID`, `Nm`, `Address`, date_format(`DateOfBirth`, '%d%M%Y') as DateOfBirth 
  FROM `PersonalDetails` where `UserMasterID` = '{$userid}'
") or die (mysql_error());

It should run now.

Joseph
If you are going to downrate me (whoever it was), at least put in a comment as to why.
Joseph
A: 

Ehhh - why don't you concatenate ?

"SELECT `ID`, `Nm`, `Address`, date_format(`DateOfBirth`, '%d%M%Y') as DateOfBirth 
FROM `PersonalDetails` where `UserMasterID` = '" . $userid . "'";

but Joseph is spot on ...

Mike
@Mike - please don't ever write a query this way... it exposes various security risks, such as SQL injection attacks.
Sohnee