Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Full MySQL Query String on Insert or Update

Tags:

Need help with MySQL as it's not really my forte. So any help is appreciated.

I have issues on my site where UPDATE or INSERT were done with missing values. This caused some issues on other functions on the site, but I am not able to find where the UPDATE or INSERT were done in any of the classes.

Is there any way, maybe a MySQL trigger, that I could add to these tables that would allow me to store the original or full query of the UPDATE or INSERT. I have tried logging but that applies to the whole database and it takes up too much diskspace.

Thanks in advance for any replies.

PS: At the moment, the PHP classes are a bit messy as we're still in the development stage, so adding exceptions to the updates or inserts functions will take too much time. So please focus the answer to the question. Thanks again.

like image 803
asyadiqin Avatar asked May 17 '12 00:05

asyadiqin


People also ask

Is insert same as update in MySQL?

Insert is for adding data to the table, update is for updating data that is already in the table. Show activity on this post. An UPDATE statement can use a WHERE clause but INSERT cannot.

How do I find the length of a string in MySQL?

MySQL LENGTH() Function The LENGTH() function returns the length of a string (in bytes).

Does MySQL support select top?

Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses FETCH FIRST n ROWS ONLY and ROWNUM .


2 Answers

You can get the current SQL query as a string with the following statement:

SELECT info FROM INFORMATION_SCHEMA.PROCESSLIST WHERE id = CONNECTION_ID() 

So what you have to do is to create a TRIGGER which runs on insert and/or update operations on your table which should (i) get the current sql statement and (ii) insert it into another table, like so:

DELIMITER |  CREATE TRIGGER log_queries_insert BEFORE INSERT ON `your_table` FOR EACH ROW BEGIN     DECLARE original_query VARCHAR(1024);     SET original_query = (SELECT info FROM INFORMATION_SCHEMA.PROCESSLIST WHERE id = CONNECTION_ID());     INSERT INTO `app_sql_debug_log`(`query`) VALUES (original_query); END; | DELIMITER ; 

You will have to create two triggers - one for updates and one for inserts. The trigger inserts the new query as a string in the app_sql_debug_log table in the query column.

like image 63
Itay Grudev Avatar answered Sep 28 '22 09:09

Itay Grudev


I think you need to check General Query Log of your db server.

The server ... ... logs each SQL statement received from clients. ... ... Since MySQL 5.1.6 log can be a file or a table.

like image 21
Ravinder Reddy Avatar answered Sep 28 '22 10:09

Ravinder Reddy