Magento Themes and Magento Extensions

Magento – How to run Query from magento root file?

Share

In magento some time you need to truncate some tables or you need to find some details using sql query
If you don’t have the database access credentials only ftp access then create the .php file and write some query into that which you want to execute one sample is as below

here I am truncating the table called ‘catalog_product_flat_1′


<?php
/***********************
* Scan Magento local.xml file for connection information
***********************/

if (file_exists('./app/etc/local.xml')) {

$xml = simplexml_load_file('./app/etc/local.xml');

$tblprefix = $xml->global->resources->db->table_prefix;
$dbhost = $xml->global->resources->default_setup->connection->host;
$dbuser = $xml->global->resources->default_setup->connection->username;
$dbpass = $xml->global->resources->default_setup->connection->password;
$dbname = $xml->global->resources->default_setup->connection->dbname;

$tables = array(
'catalog_product_flat_1', // if you want to add another table add here or below
);

}

else {
exit('Failed to open ./app/etc/local.xml');
}

/***********************
* Start HTML output
***********************/

/** Output title, connection info and cron job monitor runtime **/

echo "www.yourdomainname.com
Connection: ".$dbuser."@".$dbhost."</br>Database: " . $dbname . "
";

/** Connect to database **/

$conn = mysql_connect($dbhost,$dbuser,$dbpass);
@mysql_select_db($dbname) or die("Unable to select database");

foreach($tables as $tblname) {
//$result  = mysql_query("SELECT COUNT(*) FROM " . $tblprefix . $tblname) or die(mysql_error());
mysql_query("TRUNCATE TABLE " . $tblprefix . $tblname) or die(mysql_error());
}

echo "Table '". $tblname . "' is Truncated";

mysql_close($conn);
?>

Leave a Reply

You must be logged in to post a comment.