PHP Order By not working - php

Here is my PHP Query, but it doesn't seem to order the results. Everything else works fine.
SELECT *
FROM `main`
WHERE `user_legacy` LIKE '%".$name."%'
ORDER BY 'user_legacy' DESC LIMIT ".$limit

You use backticks (') to quote column names in SQL, not the normal single quote (').
ORDER BY `user_legacy` DESC
Also, if you don't do any kind of vetting or your input, that query is potentially vulnerable to an SQL injection.

Don't quote the column name.
ORDER BY user_legacy

ORDER BY needs a column name, you're passing it a string. Lose the quotes.

Related

WHERE NOT EXISTS syntax error

I have this code that does not work, and im not sure why...
if(isset($_GET['id'], $_SESSION['username'])){
$id = $_GET['id'];
$user = $_SESSION['username'];
$query = $handler->query("INSERT INTO photolikes('User', 'Photo')
SELECT '$user', '$id'
WHERE NOT EXISTS (SELECT Id FROM photolikes WHERE User='$user' AND Photo=$id)");
}else{
}
Is just supposed to insert user and photo into a table if there is no such in there before... thanks for any help!
The SELECT is missing the FROM clause which is required when a WHERE clause is used.
That's the problem.
There's a couple of ways to fix it.
For a quick fix, you can add FROM DUAL before the WHERE.
If you don't like your MySQL queries looking like they are Oracle queries, you can use an inline view as a rowsource.
In place of FROM DUAL you could use FROM (SELECT 1) i.
That's the less-Oracle-more-MySQL-like way of fixing it. That's how I would do it.
You could also reference any table or view that you are guaranteed returns exactly one row. (It can't be zero rows, and it can't be two rows.
A couple other notes:
In MySQL, identifiers (for example column names) can be escaped with backtick characters, but not single quotes. Identifiers only need to be escaped if they contain characters that aren't allowed (in unescaped identifiers) or if the identifier conflicts with a reserved word.
INSERT INTO photolikes(`User`, `Photo`)
^ ^ ^ ^
Also, the code appears to be vulnerable to SQL Injection. Potentially unsafe values that are incorporated into the text of a SQL statement should be properly escaped. But an even better pattern is to use prepared statements with bind placeholders.
INSERT INTO photolikes(`User`, `Photo`)
SELECT '$user', '$id'
FROM <someTable>
^^^^ you miss the FROM
WHERE NOT EXISTS (SELECT Id
FROM photolikes -- Here you didnt forget.
WHERE User='$user' AND Photo=$id)")

MySQL: Query with ORDER BY clause returns nothing

In my MySQL database, I have a table called pages and it contains several columns, two of which are order (int), tab (int), and name (text). When I call a query as such
"SELECT * FROM pages WHERE tab = '$tid'"
it executes with no problem, returning all rows with the correct tab label. The problem I am having is when I execute with an ORDER BY :
"SELECT * FROM pages WHERE tab = '$tid' ORDER BY order ASC"
I get a return of false from the query. No errors either.
When I put the column order in single quotes ', the query works like it did before, but applies no order.
Why am I getting no return regardless of which column I try to sort by? How do I make my query sort to a column correctly?
ORDER is a reserved word in MySQL, so you should escape it with backticks ` if you want to use it as an identifier :
SELECT * FROM pages WHERE tab = '$tid' ORDER BY `order`
You are getting an error is not coming out. Try the following:
select * from pages order by `order`;
ORDER is a reserved word. If you not quote it properly the query will not run.

SQL query: Can't order by column called "order"?

I am pulling a column in an existing script into my template files, and everything is working great.
The only problem is, that this script has a column called order, and every row then has a number in that column to show which should be at the top etc. If I set my query to "ORDER BY name" for example, everything works fine, but when I use "ORDER BY order", then I get a SQL error.
Can I not have a column called order? I can't change column name, because it's part of the script.
Is there a way around it?
This is the line in my SQL query:
SELECT * FROM categories WHERE hide = 0 ORDER BY order
order is a keyword in SQL. So if you wish to use a keyword as a name, use backtick characters around it:
SELECT * FROM categories WHERE hide = 0 ORDER BY `order`
Try that :)
If you are working with Postgres just use "column_name", e.g:
SELECT "order" FROM table_name WHERE "order" > 10 ORDER BY "order";
AS orderis a SQL keyword, you should escape it properly as an field identifier by using backticks:
SELECT ... FROM ... ORDER by `order`
Try using backticks:
SELECT * FROM `categories` WHERE `hide` = 0 ORDER BY `order`
ORDER is a reserved word in SQL. You can use a reserved word as a column name but you must surround it in backticks when referencing it. It's good practice to surround all your column names in backticks so you don't run into this issue.
Try using back ticks around the column name, that should do it.
From the manual:
A reserved word can be used as an identifier if you quote it.
So you can use it like this:
SELECT * FROM categories WHERE hide = 0 ORDER BY `order`
Worked for me with brackets. SELECT T.* FROM dbo.test AS T ORDER BY [T].[ORDER]

Error in query syntax

i am using ORDER BY in mysql SELECT query but i dont know ots not ordering the data.. if i use this query its showing the table but not ordering the data in ascending order
$result = mysql_query("SELECT *FROM learningmaterial ORDER BY 'order' ASC")or die(mysql_error());
but if i use
$result = mysql_query("SELECT *FROM learningmaterial ORDER BY order ASC")or die(mysql_error());
then it give error that the syntax of the query is not right...i've seen on various sites but i couldnot found anything unique in my code...i think its right,...please check the query and mend a solution. Thankx in advance :)
You need backticks, not single quotes (a):
... SELECT * FROM learningmaterial ORDER BY `order` ASC ...
By using single quotes, you're ordering the rows by a constant (each row gets the same constant) so effectively not ordering them at all.
By using a "naked" column name of order, you're confusing the SQL parser, since order is a reserved word.
(a): Of course, this problem goes away if you stop using reserved words as column names but I assume you did that for a reason (such as a bucket-load of programs already depending on the fact that the column is called order).
Myself, I tend not to use generic names for columns (such as order or date), preferring instead things that don't conflict with the language (such as order_num or start_date). That way I don't have to worry about escaping.
You are using SQL reserved keyword order as a column name so use back-ticks to escape...like this
SELECT * FROM learningmaterial ORDER BY `order` ASC
I would suggest you to change the columnn name
Reference For List Of Reserved Keywords
ORDER is a reserved sql syntax keyword. you cannot use it directly
SELECT *FROM learningmaterial ORDER BY `order` ASC
-------------------------------^---------
in second case
SELECT *FROM learningmaterial ORDER BY order ASC
---------------------------------^-------^--
//this is a sql error
it doesn't make any sense.
Since Order is a reserved word, you need to wrap them using backticks not single quotes.
SELECT * FROM `learningmaterial` ORDER BY `order` ASC

Is this MySql Query Statement correct?

I would like to know whether this MySql statement will be executed correctly,
"SELECT sum(price) FROM products WHERE productid IN (SELECT productid FROM shoppingcart WHERE sessionid=".$this->$sessionid.")"
And if not please give me pointers as to where I am wrong.
Thanks
I'm sure you meant
$this->sessionid
not
$this->$sessionid
(the second one returns value of property, which name is stored in sessionid, thus, when $sessionid is 'abcdef', it tries to return value of $this->abcdef property).
Also, enclose in ' AND escape all parameters.
"SELECT sum(price) FROM products WHERE productid IN (SELECT productid FROM shoppingcart WHERE sessionid='".mysql_escape_string($this->sessionid)."')";
i am using sql server but i think error over here is
single quote ' is required for session id
"SELECT sum(price) FROM products WHERE productid IN (SELECT productid
FROM shoppingcart WHERE sessionid='".$this->$sessionid."')"
Seems fine to me.
As #praynay said, I believe you need quotes around the session id.
Also, be very, very sure $this->sessionid will not have a quote character in itself, or that you escape it properly before passing it to MySQL. (Or better yet, use a parameterized query.)

Categories