Jump to content

MySQL order by query not working?


guru62

Recommended Posts

WHAT AM I DOING WRONG IN THIS QUERY???

 

 

"SELECT

topic_id,

topic_subject,

topic_date,

topic_cat

 

FROM

topics

 

ORDER BY topic_date DESC

 

 

 

WHERE

topic_cat = " . mysql_real_escape_string($_GET['id']);

 

if i remove the order by bit it works but i want my results to come back ordered. this query wont work.

 

 

i recieve 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 'WHERE topic_cat = 1' at line 14

 

this query is to be echoed using php on html page

Link to comment
https://forums.phpfreaks.com/topic/259827-mysql-order-by-query-not-working/
Share on other sites

$sql = "SELECT	
				topic_id,
				topic_subject,
				topic_date,
				topic_cat

			FROM
				topics 



				WHERE
				topic_cat = "  . mysql_real_escape_string($_GET['id'])

				ORDER BY topic_date DESC;

 

i tried this now and the page doest even open i get a http 500 error, i think this fails to run

$sql = "SELECT	
				topic_id,
				topic_subject,
				topic_date,
				topic_cat

			FROM
				topics 



				WHERE
				topic_cat = "  . mysql_real_escape_string($_GET['id'])  . "


				ORDER BY topic_date DESC";

 

I got it, the whole time I forgot to concatenate! Thanks for reminding me, its been bugging me for 2 hours!  :wtf:

 

Also I know we have to use quotes after topic_cat = ", but why does the query not work without it, is it something to do with concatenation of a php function?

Good job!

 

functions cannot be inside of strings, otherwise they are just text.

Variables ($var) can be inside of a double quoted string, but not a single quoted.

Speaking of which, best practice would be to have your query in single quotes.

Even better, if you know $id should be an int, use something like intval() rather than the escape string function.

then why doesnt this query for example in another script of mine need concatenation?

 

$sql= "SELECT
		categories.cat_id,
		categories.cat_name,
		categories.cat_description,
		COUNT(topics.topic_id) AS topics
	FROM
		categories
	LEFT JOIN
		topics
	ON
		topics.topic_id = categories.cat_id
	GROUP BY
		categories.cat_name, categories.cat_description, categories.cat_id";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.