8

When I click on a button, an AJAX-call is being made to my self written API. When the button is clicked, the Javascript file retrieves two data-attributes from the clicked object and sends it along with the URL. The two variables are used in the where clause of the yet to be executed SQL-statement.

When the call is being made, the PHP-script that handles the API requests receives the two variables via Input::get('data-attribute-one')) and Input::get('data-attribute-two')). When I output these two attributes, the correct values are displaying.

However, when I put the variables into the where-clause of my query, like so:

$fans = Sensor::where('fan_number', '=', $dataAttributeOne)->where('created_at', '>=', $this->now->subHours(6))->get();

no results are returned. So I replaced ->get() with ->toSql() to check the query and it presented me with this strange line of code:

Object {fans: "select * from "myawesomedatabasetable" where "fan_number" = ? and "created_at" >= ?"}

$dataAttributeOne is the retrieved data-atribute and $this->now->subHours(6) is the current time minus 6 hours. When I output this, it is in the same format as the created_at value in the database and when I hardcode it into an SQL-statement in Phpmyadmin, the query executes like a charm. So no problems there.

So my question is: why are the variables turning into question marks when the query executes and how do I solve this?

Thanks in advance!

Kevin Kromjong
  • 174
  • 3
  • 13
  • 1
    Simple answer to your question `Why are the variables turning into question marks when the query executes` they are placeholders as part of [prepared statements](https://en.wikipedia.org/wiki/Prepared_statement) it is **not** executed as that, as Alexey has answered is your solution. – Ash Apr 20 '16 at 08:21

1 Answers1

10

That's just how toSql() works. This method is used for debugging.

https://scotch.io/tutorials/debugging-queries-in-laravel

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • I feel very stupid now.. But I read through the link, installed the Debugbar and figured out what part of the prepared statement went wrong. Thanks! – Kevin Kromjong Apr 20 '16 at 08:56
  • Another way to debug sql queries is to turn on mysql debugging so that it logs all queries that have run. see: http://stackoverflow.com/questions/6479107/how-to-enable-mysql-query-log – Mysteryos Apr 20 '16 at 09:52