Sandra Larsson
Sandra Larsson

Reputation: 11

You have an error in your SQL syntax - syntax to use near 'WHERE userId = '6'' at line 1

I get the error

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE userId = '6'' at line 1

When querying these lines:

$query = 'SELECT * FROM post ORDER BY created DESC ';
    $query .= 'WHERE userId = \'' . mysqli_real_escape_string($db, $userId) . '\'';

Can't find a solution. Do need to change in the column for the db or in the syntax?

Upvotes: 0

Views: 783

Answers (4)

Magisch
Magisch

Reputation: 7352

Multiple errors with your query:

$query = 'SELECT * FROM post ORDER BY created DESC ';
  1. ORDER BY follows after WHERE in the syntax flow, so specifying a WHERE after ORDER BY is a syntax error (what you're getting)

    $query .= 'WHERE userId = \'' . mysqli_real_escape_string($db, $userId) . '\'';

  2. You're not actually using parameterized queries. Get familiar with them and use them, mysqli_real_escape_string is only a bandaid to using proper parameters.

  3. You're comparing a userID (presumably a integer) using string notation. That is pointless and may lead to unwanted results. Integers do not need to be enclosed in quotation marks in SQL.

"Repaired" Code for your query (still look up how to parameterize though):

$query = 'SELECT * FROM post WHERE userID = '.mysqli_real_escape_string($db, $userId).' ORDER BY created DESC';

Upvotes: 1

Shital Marakana
Shital Marakana

Reputation: 2887

use ORDER BY after WHERE. in query

<?php
$query = 'SELECT * FROM post';
$query .= ' WHERE userId = "' . mysqli_real_escape_string($db, $userId) . '"';
$query .= ' ORDER BY created DESC';
?>

Upvotes: 0

delboy1978uk
delboy1978uk

Reputation: 12365

Did you even try echoing the query? You'll see there's no space between DESCWHERE.

Move the ORDER BY to the end.

SELECT whatever FROM wherever WHERE whatever ORDER BY whatever

Also, read up on PDO and prepared statements, that code is vulnerable to SQL injection. https://phpdelusions.net/pdo

Upvotes: 0

Lovepreet Singh
Lovepreet Singh

Reputation: 4840

Error due to use of WHERE after ORDER BY. The proper query should be as:

$query = 'SELECT * FROM post WHERE userId = "' . mysqli_real_escape_string($db, $userId) . '" ORDER BY created DESC';

Upvotes: 1

Related Questions