Optimize Mysql Table with PHP script

Posted by Shek on November 19, 2012 under MySQL, PHP | Be the First to Comment | Total View: 8,051 views

In this post, I am going to show how to optimize Mysql Table with PHP script. This could become handy when a Mysql table often has overhead and needs to be optimized.


The easiest way to optimize mysql table is to be done through phpMyAdmin as it has a build in function to optimize the mysql table. However, when the mysql table generates overhead very often then it is better to be done automatically, PHP with crontab is a good idea.

First the sql to optimize mysql table is:

1
OPTIMIZE TABLE tablename

To use PHP to run the SQL:
First connect to the database

1
2
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");

Then run the SQL with the function mysql_query():

1
2
3
4
5
6
7
8
9
$result = mysql_query("OPTIMIZE TABLE tablename" );
if (!$result) 
{
   echo "fail";
}
else
{
   echo "done";
}

All together we have:

1
2
3
4
5
6
7
8
9
10
11
12
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
 
$result = mysql_query("OPTIMIZE TABLE tablename" );
if (!$result) 
{
   echo "fail";
}
else
{
   echo "done";
}

Not what you want? Try a Search

Add A Comment

*