Monday, January 19, 2009

Enahncement to mysql_query php function.

I have extended mysql_query function to have more flexibility. It is a php file say "run_query.php". Include this file in your php application. To use this file follow these steps.
1) Create a table in mysql with the following structure.
CREATE TABLE `errorlog`
( `query` varchar(5000) default NULL,
`error` varchar(5000) default NULL )

2) Create a php file and paste following code. Save the file (say file name is run_query.php).

< ? php
function mysql_query_($query)
{ // Paste here code to connect to mysql database.
$username='root';

$password='';
$host='localhost';
$db_name="xyz";
$conn1=mysql_connect($host,$username,$password) or die("Unable to connect to mysql server");
$select1=mysql_select_db("$db_name",$conn1) or die("Unable to connect to mysql database");
$curdate = date("d-m-Y H:i:s");
if(mysql_query($query) == true) // The queri is fired and checked.
{
if(substr(strtoupper($query),0,6) == 'INSERT' substr(strtoupper($query),0,5) == 'UPDATE' substr(strtoupper($query),0,5) == 'DELETE') // The query is checked for Insert/Update/Delete
{
$fp=fopen("trans.sql","a"); //If query is type of Insert/Update/Delete then it will store the query into trans.sql file.
if($fp==null)
{
die("File cannot be opened. Try again !!!");

}
$printline = "/* $curdate : */ $query ;";
fprintf($fp,"\r\n%s",$printline);
fclose($fp);
return true;
}
else
{
return mysql_query($query);
}
}
else
{
$error = mysql_error();
$error = addslashes($error);
$query = addslashes($query);
mysql_query("insert into errorlog values('$query','$error')");
return false;
}
}
? >

3) Include this file in your any php application. (Command to include file : )
4) Use mysql_query_ function instead of mysql_query function.
e.g.
/*< ? php $query = "select * from employee";
$result = mysql_query _($query)
? >
*/
Advantages.
  1. You can log query and error in your database table (errorlog).
  2. A sql file created/appendended whenever any Data manipulation query is fired. So you can have a complete transaction log in query format.
  3. This sql "trans.sql" file will help you in "point in time recovery" in case of the database is crashed.
Your views ,comments and updation in this function are welcome.
Please mail on girishpadia@gmail.com

No comments: