0

I'm having an issue with a prepared statement with a parameter, please see below.

I apologise in advance if this turns out to be some dumb mistake.

The error:

Failed to run query (Project List) - SQLSTATE[42000]: Syntax error or access violation: 1064 
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 ''0,8'' at line 1

The code:

$limit = ($pagenum - 1) * $page_rows . "," . $page_rows;

print_r($limit); // Prints 0,8 as expected

$query = "SELECT * FROM projects INNER JOIN users ON projects.companyid = users.companyid ORDER BY projects.projectid DESC LIMIT :limit";

$query_params = array (
    ':limit' => $limit
);

try {
    $stmt = $db->prepare($query);
    $stmt->execute($query_params);
}
catch (PDOException $ex) {
    die("Failed to run query (Project List)" . " - " . $ex->getMessage());
}

What I've tried so far:

  • Added the SQL Limit as part of the $limit string
  • Renamed the limit parameter/variables just in case (reserved keyword etc)
  • Tested the SQL query manually in SQLyog with the LIMIT 0,8 - works fine
  • Tested the prepared statement by directly passing the limit variable - works fine
  • Read all similar questions suggested, no similar issues found at least within my level of understanding.
Danieloplata
  • 222
  • 2
  • 9

1 Answers1

4

Your $limit parameter is being escaped as one parameter, where it should be escaped as two. Your sql will currently look something like "limit '0, 8';" where it should look like "limit 0, 8";

To solve this, you should split your limit parameter into two. Edit the end of your SQL to look like:

LIMIT :offset, :limit

And your parameter list to look like:

$query_params = array (
    ':offset' => ($pagenum - 1) * $page_rows,
    ':limit' => $page_rows
);

As Mr Smith mentioned, you'll also have to add the line:

$db->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

To ensure the limit parameters are correctly handled as integers rather than strings.

Simon Brahan
  • 2,016
  • 1
  • 14
  • 22
  • Thank you for a very clear answer. I did have some concerns that in the SQL error message my limit variable looked like it was being treated as a string. – Danieloplata Sep 09 '14 at 12:20