A PHP Record of All MySQL Queries

A PHP Record of All MySQL Queries thumbnail
A record of all your queries tells you about how visitors are using your site.

PHP's libraries for utilizing the open source database software MySQL makes it easy for even PHP novices to create database-driven websites with dynamic content. The fact remains, however, that they are two very separate software components. This means that if you want a record of all the MySQL queries your PHP scripts execute, you will have to add that mechanism yourself.

  1. MySQL Server

    • The PHP interpreter translates the PHP source code into machine executable code, and MySQL runs as a separate software server. Just as a physical server stores data that any computer on the Internet can access, the MySQL server holds data that any program on the system can access. Consequently, if you want a record of all the MySQL queries from your PHP scripts, you will have to add a few lines to your PHP source code files.

    PHP MySQL Queries

    • The basic process for having PHP scripts query MySQL databases is to establish a connection with the MySQL server, send the query, receive the results from the MySQL server, and then close the connection. The query itself takes the form of a text string. The simplest way to record a query is to put the MySQL query syntax in its own variable, pass that variable into the query function, and then use that same variable in making the query log.

    Recording Queries

    • The easiest way to write a PHP query log file is with the "fopen()" and "fwrite()" functions. Using the syntax "$query_records = fopen('directory', 'a');" to create an object for the log file called "$query_records." In this syntax, "directory" is the full directory address for the log file. Then, use the command "fwrite($query_records, $query + '\n');" to write the query to the end of the file. In this command, "$query" is the name you gave the variable holding the MySQL query.

    Accessing Records

    • If you add the code to record the PHP scripts' MySQL queries, then you have two options for viewing the record of all those queries. The log file will be in plain text format, so you can open it with a text viewer. You can also write another PHP script to act as a log viewer. Use the command "$query_records = fopen('directory', 'r');" to open the log file; then use the command "fgets($query_records);" to get the first query on record. Each time you call the "fgets" command, it will return the next query on record. You can keep using the command until it returns the boolean value "false," meaning that you have reached the end of the log file.

Related Searches:

References

  • Photo Credit Comstock Images/Comstock/Getty Images

Comments

Related Ads

Featured