1

I often get problems with mysql queries that are malformed in the codebase I'm working on. Unfortunately, the error that gets passed back is usually very unhelpful:

Mysql error: [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 ':status0 OR FlagStatus = :status1 )  ORDER BY OrderId DESC, GiftCardId DESC' at line 1]

Because I'm frequently using a dynamically generated query, and don't know what the original query looked like when it went in (unlike when I'm using the command line), so the errors often start just after the information that would actually be useful.

So... ...is there some way for me to get the last query that was used, so that I can display the full query after the mysql error is thrown?

Kzqai
  • 22,588
  • 25
  • 105
  • 137
  • I actually used this answer: http://stackoverflow.com/questions/650238/how-to-show-the-last-queries-executed-on-mysql And started logging on the mysql.general_log table, at least as a temporary solution. – Kzqai Dec 01 '11 at 16:12

3 Answers3

3

Must this be done in PHP?

You could use MySQL's query log.

simshaun
  • 21,263
  • 1
  • 57
  • 73
  • I wouldn't mind doing that if there were anything in my logs.... ...everything that looks like it would be for mysql... ...is empty? Maybe I have to go through steps to make the log active somewhere in my php, I guess? I'll try looking into it from that approach. – Kzqai Dec 01 '11 at 16:02
2

Why can't you keep track of it yourself?

$query = 'SELECT ...';
$result = mysql_query($query);
if (!$result) {
    echo mysql_error() . ' in ' . $query;
}
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Well... ...I do have a wrapper around the sql that I'm executing, but the error stops execution, so I'd have to suppress that error somehow to then display all the rest of the information, and I'm using the wrapper around PDO, and the code for displaying the errors is quite separate from the code for executing the sql and well, it all gets complicated at that point. I was hoping there was a simpler way. – Kzqai Dec 01 '11 at 15:51
2

You might want to read this

If you find that too much trouble, you could always log the queries yourself by storing them in a file.

Also, why don't you use PHPMyAdmin to test queries? Oh, edit: Just noticed that you said the queries are dynamically created, sorry.

Joel Murphy
  • 2,472
  • 3
  • 29
  • 47
  • I test the sql in the command line, but I just get errors when something's off in the dynamically generated sql syntax and the errors are so often useless. – Kzqai Dec 01 '11 at 15:52