1

i made this:

$query1=mysql_query("select id, testo, titolo from events order by DESC WHERE id < 225 LIMIT 1");
while($query2=mysql_fetch_array($query1))
{
echo $query2['titolo'];
}

But doesn't work, i don't understand why, someone can help me? I think the problem is in the query.

UPDATE: I made two mistakes:

The first: i have missing the column name in order by clause. The second: The position of ORDER

  • 1
    Do you look at the manual? http://dev.mysql.com/doc/refman/5.7/en/select.html. `select ...from... where... order...limit`. – chris85 Feb 02 '16 at 17:40
  • @chris85 cool explanation :) – devpro Feb 02 '16 at 17:54
  • @chris85: Thanks for your link. I have added it in my answer :) – Ravi Hirani Feb 02 '16 at 17:58
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Feb 02 '16 at 18:29

4 Answers4

5

Write your query as below:-

SELECT id, testo, titolo FROM events WHERE id < 225 ORDER BY id DESC LIMIT 1

As suggested by chris85, For understanding select ...from... where... order...limit,

This link is very useful.

Hope this will help you :)

Community
  • 1
  • 1
Ravi Hirani
  • 6,511
  • 1
  • 27
  • 42
2

You are using ORDER BY before WHERE Clause you can not get the result like this way.

Second issue is that you didn't mentioned the id column or any other column in ORDER BY.

Modified Query:

SELECT id, testo, titolo FROM events WHERE id < 225 
ORDER BY id DESC
LIMIT 1

Side note:

Please use mysqli_* or PDO instead of mysql_* becuase this extension deprecated and not available in PHP 7.

devpro
  • 16,184
  • 3
  • 27
  • 38
1

you have at least 2 errors. Rewrite your query to look like:

SELECT id, testo, titolo FROM events WHERE id < 225 ORDER BY id DESC LIMIT 1
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
0

You're missing the column name in your order by clause. That section should be something like order by col_name desc. Also the where clause comes before the order by as described in above answers.

Steve Wakeford
  • 331
  • 1
  • 8