Empty database in MySQL and PHP? - php

Is it possible to empty an entire database by connecting to it with PHP and giving a command?

The simplest way to do it, if you have the privileges, is:
DROP DATABASE dbName;
CREATE DATABASE dbName;
USE DATABASE dbName;
The alternative is to query the information_schema database for triggers, stored routines (procedures and functions), tables, views and possibly something else, and drop them individually.
Even after this, your database might still not be in the same state as a newly created one, since it might have a custom default character set and collation set. Use ALTER DATABASE to change that.
As features keep getting added (events...) you'll have more and more work this way. So really, the only way to completely empty the database is to drop it and re-create it.

You can get table names with
SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'your db'
And make the truncate,
even, you can make
SELECT 'TRUNCATE TABLE ' + table_name + ';' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'your db'
And then iterate the resultset executing the string query for each record.

You can get a list of all tables in a database ($databaseName), loop through them all, and apply TRUNCATE TABLE to each.
$result = mysqli_query($link, "SHOW TABLES IN `$databaseName`");
while ($table = mysqli_fetch_array($result)) {
$tableName = $table[0];
mysqli_query($link, "TRUNCATE TABLE `$databaseName`.`$tableName`");
if (mysqli_errno($link)) echo mysqli_errno($link) . ' ' . mysqli_error($link);
else echo "$tableName was cleared<br>";
}
This clears the contents of all the tables in a database, keeping the structure.

Yes. Basically, you need to get a list of all Tables in the Database, then iterate over that list and issue a TRUNCATE TABLE $tablename for each entry.
This looks like a decent enough implementation: Truncate all tables in a MySQL database

This worked for me.
mysql -u < DB-USER > -p<DB-PASS> --silent --skip-column-names -e "SHOW TABLES" <DB-NAME> | xargs -L1 -I% echo 'DROP TABLE `%`;' | mysql -u < DB-USER > -p< DB-PASS > -v < DB-NAME >

<?php
$connection = new mysqli($host, $user, $pass, $db);
$sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE '".$db."'";
$result = $connection->query($sql);
$tables = $result->fetch_all(MYSQLI_ASSOC);
foreach($tables as $table) {
$sql = "TRUNCATE TABLE `".$table['TABLE_NAME']."`";
$result = $connection->query($sql);
}
?>

Yes. You can connect the database and Truncate the table by assigning as a variable.
$conn = new mysqli($servername, $username, $password, $dbname);
$variableName = $conn->query($que);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query('TRUNCATE TABLE yourtablename;');
if ($result) {
echo "Request ID table has been truncated";
}
else echo "Something went wrong: " . mysqli_error();

Related

MySQL copy table to different database with same credentials

I am using the standard MySQL functions that PHP has built in for copying one table to an new table.
This works perfect when the tables are in the same database. But I want to copy it to another databasename with same user and password.
Any suggestions how to achive this?
(Since $database can only contain 1 databasename)
Error shown is Table 'torzahttp_rsw.torzahttp_rsw.kwaliteit' doesn't exist
torzahttp_rswis the database name, and kwaliteit the table name.
Why is the databasename used twice?
// Create a new MySQL database connection
if (!$con = new mysqli('localhost', $username, $password, $database)) {
die('An error occurred while connecting to the MySQL server!<br><br>' . $con->connect_error);
}
// Create an array of MySQL queries to run
$sql = array(
'DROP TABLE IF EXISTS `backup_db.backup_table`;',
'CREATE TABLE `backup_db.backup_table` SELECT * FROM `live_db.live_table`'
);
// Run the MySQL queries
if (sizeof($sql) > 0) {
foreach ($sql as $query) {
if (!$con->query($query)) {
die('A MySQL error has occurred!<br><br>' . $con->error);
}
}
}
$con->close();
From the MySQL manual:
If any components of a multiple-part name require quoting, quote them individually rather than quoting the name as a whole. For example, write `my-table`.`my-column`, not `my-table.my-column`.
Your code:
$sql = array(
'DROP TABLE IF EXISTS `backup_db.backup_table`;',
'CREATE TABLE `backup_db.backup_table` SELECT * FROM `live_db.live_table`'
);
should look like this:
$sql = array(
'DROP TABLE IF EXISTS `backup_db`.`backup_table`;',
'CREATE TABLE `backup_db`.`backup_table` SELECT * FROM `live_db`.`live_table`'
);
Or, just drop the backticks altogether.
I have used this solution to create an mysql dump first and then processioning it.
//DB
$user = 'xxxxx';
$password = 'xxxxx';
$host = 'localhost';
$database_old = 'old_db';
$database_new = 'new_db';
$table = 'kwaliteit';
$file = 'kwaliteit.sql';
exec('mysqldump --user='.$user.' --password='.$password.' --host='.$host.' '.$database_old.' '.$table.' > uploads/'.$file);
exec('mysql --user='.$user.' --password='.$password.' --host='.$host.' '.$database_new.' < uploads/'.$file);
unlink('uploads/'.$file);

mysql Show tables returns all +1 with TABLES "number of rows" as first value

When i recently wanted to list all tables in a database in php i made the simple MySQL query:
$tables_query = mysql_query('show tables');
while ($test = mysql_fetch_array($tables_query)) {
echo "Table: {$test[0]}<br />";
}
The first result is
TABLES 105
address_book
I don't have a table called "TABLES 105" but the mysql_num_rows also shows, that there is 105 results, even that my database only contains 104 table
If i try to request "show tables" directly on the MySql server, it works fine and i get 104 rows as result. It also worked before and i can't seem to find anything about this, so im hoping someone can help me in here.
It also affect when i call directly to the mysql server. I got access with an other user login for an other database, on the same server and here is no issues at all.
Its questionable how that 105 got there in the first place, most likely this is caused by that mysql_num_rows function that you mentioned as fetch_array actually fetches the rows, but here's one on MySQLi, stop using MySQL anymore:
$db = 'test'; // database name
$con = mysqli_connect('localhost', 'username', 'password', $db);
$tables_query = mysqli_query($con, "SHOW TABLES FROM {$db}");
while($table = mysqli_fetch_assoc($tables_query)) {
echo $table["Tables_in_{$db}"], '<br/>';
}
An alternative way of course is to delve into information_schema:
$db = 'test'; // database name
$con = mysqli_connect('localhost', 'root', '', $db);
$tables_query = mysqli_query($con, "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{$db}'");
while($table = mysqli_fetch_array($tables_query)) {
echo $table['TABLE_NAME'], '<br/>';
}

MySQL Transaction+ PHP issue in Mysql

I have a code which was used in an application where I am having a problem in rollback. Even if I 's2' returns false rollback isn't happening i.e. table 'products' is getting droped.
Can anyone explain why it isn't working or how should I change it.
Note: tables are of Innodb engine..I use mysql 5.0+
mysql_query('SET AUTOCOMMIT=0;');
mysql_query('START TRANSACTION;');
$sql = 'DROP TABLE '.$this->Product->tablePrefix.'products';
$s1 = mysql_query($sql);
$sql = 'RENAME TABLE '.$this->Product->tablePrefix.'temp12212 TO '.$this->Product->tablePrefix.'products';
$s2 =mysql_query($sql);
if($s1 && $s2){
mysql_query('COMMIT;');
$this->Session->setFlash('Commit Successful to Database');
}else{
mysql_query('ROLLBACK;');
$this->Session->setFlash('Commit failed due to some errors<br> auto-rollbacked to previous state');
}
DROP TABLE is one of the commands in MySql that cause a implicit commit.
http://dev.mysql.com/doc/refman/5.1/en/implicit-commit.html
Use this instead:
'RENAME TABLE '.$this->Product->tablePrefix.'products TO backup_table
, '.$this->Product->tablePrefix.'temp12212 TO '.$this->Product->tablePrefix.'products';
You cannot rollback a DROP TABLE or RENAME TABLE statement as they cause an implicit commit.
I sorted the problem this way instead!!! thanks all for your reply :-)
$sql = 'DROP TABLE IF EXISTS '.$this->Product->tablePrefix.'temp_backup';
mysql_query($sql);
$sql = 'RENAME TABLE '.$this->Product->tablePrefix.'products TO '.$this->Product->tablePrefix.'temp_backup, '.$this->Product->tablePrefix.'temp TO '.$this->Product->tablePrefix.'products';
$status =mysql_query($sql);
if($status){
$sql = 'DROP TABLE '.$this->Product->tablePrefix.'temp_backup';
mysql_query($sql);
$this->Session->setFlash('Commit Successful to Database');
}else{
$this->Session->setFlash('Commit failed due to some errors<br> auto-rollbacked to previous state');
}

How to drop all tables in database without dropping the database itself?

I would like to delete all the tables from database, but not deleting the database itself. Is it possible ? I'm just looking for shorter way than removing the database and create it again. Thanks !
The shortest is to re-create database. but if you don't want to...
This is for MySQL/PHP. Not tested but something like that.
$mysqli = new mysqli("host", "my_user", "my_password", "database");
$mysqli->query('SET foreign_key_checks = 0');
if ($result = $mysqli->query("SHOW TABLES"))
{
while($row = $result->fetch_array(MYSQLI_NUM))
{
$mysqli->query('DROP TABLE IF EXISTS '.$row[0]);
}
}
$mysqli->query('SET foreign_key_checks = 1');
$mysqli->close();
There is no simple way to do this. Either you'll need to know what the tables are in advance:
//edit you can get this information using the query SHOW TABLE STATUS
$tables = array('users','otherdata');
foreach($tables as $table){
db.execute("DROP TABLE "+$table);
}
or you can drop the database and re-create it empty (it's really not that much effort!):
db.execute('DROP DATABASE SITEDATA');
db.execute('CREATE DATABASE SITEDATA');
You'd have to drop every table in the db separately, so dropping the database and recreating it will actually be the shortest route (and the fastest one for that matter).
When I had to do this in Oracle, I would write a select statement that would generate the drop table statements for me. Something to the effect of:
Select 'DROP TABLE ' || table_name || ';' from user_tables;
I could then pipe the output of the select statement to a file. After I ran this, I would have a file that would drop all my tables for me. It would look something like:
DROP TABLE TABLE1;
DROP TABLE TABLE2;
DROP TABLE TABLE3;
etc...
Not a mysql expert, but I would imagine it would have a similar facility to both select all tables for a schema, as well as direct output from a SQL statement to a file.
Use SHOW TABLE STATUS to get all tables in your database, then loop over result and drop them one by one.
There are some solutions here in comments: http://dev.mysql.com/doc/refman/5.1/en/drop-table.html
I needed to drop all tables except a couple from an inadvertent dump.
A PHP function to drop all tables except some (adapted from here), for anyone else who might need:
<?php
$mysqli = new mysqli( "localhost", "user", 'password', "database");
function drop_all_tables($exceptions_array, $conn) {
$exceptions_string="('" ;
foreach ($exceptions_array as $table) {
$exceptions_string .=$table . "','";
}
$exceptions_string=rtrim($exceptions_string, ",'");
$exceptions_string .="')" ;
$sql="SELECT CONCAT('DROP TABLE ', TABLE_NAME, '; ')
FROM information_schema.tables
WHERE table_schema = DATABASE() AND table_name NOT IN $exceptions_string";
$result=$ conn->query($sql);
while($row = $result->fetch_array(MYSQLI_NUM)) {
$conn->query($row[0]);
}
}
//drop_all_tables(array("table1","table2","table3","table4"), $mysqli);
?>
A procedural way to do this is as follows:
$query_disable_checks = 'SET foreign_key_checks = 0';
$query_result = mysqli_query($connect, $query_disable_checks);
// Get the first table
$show_query = 'Show tables';
$query_result = mysqli_query($connect, $show_query);
$row = mysqli_fetch_array($query_result);
while ($row) {
$query = 'DROP TABLE IF EXISTS ' . $row[0];
$query_result = mysqli_query($connect, $query);
// Getting the next table
$show_query = 'Show tables';
$query_result = mysqli_query($connect, $show_query);
$row = mysqli_fetch_array($query_result);
}
Here $connect is just the connection made with mysqli_connect();.
You can execute this. Just add more tables if I missed any
drop table wp_commentmeta;
drop table wp_comments;
drop table wp_links;
drop table wp_options;
drop table wp_postmeta;
drop table wp_posts;
drop table wp_term_relationships;
drop table wp_term_taxonomy;
drop table wp_termmeta;
drop table wp_terms;
drop table wp_usermeta;
drop table wp_users;
The single line query to drop all tables, as below:
$dbConnection = mysqli_connect("hostname", "username", "password", "database_name");
$dbConnection->query('SET foreign_key_checks = 0');
$qry_drop = "DROP TABLE IF EXISTS buildings, business, computer, education, fashion, feelings, food, health, industry, music, nature, people, places, religion, science, sports, transportation, travel";
$dbConnection->query($qry_drop);
$mysqli->query('SET foreign_key_checks = 1');
$mysqli->close();

mysql php : switching between mysql databases is slow

In my php script which connects to mysql, I have to query 2 databases in the same script to get different information. More specifically Faxarchives in one database and Faxusers in the other.
In my code I query faxusers and then foreach user, I query Faxarchives to get the user history.
I might do something like:
function getUserarchive( $userid) {
$out= "";
$dbname = 'Faxarchive';
$db = mysql_select_db($dbname);
$sql = "select sent, received from faxarchivetable where userid = '" . $userid . "'";
if ( $rs = mysql_query($sql) {
while ($row = mysql_fetch_array($rs) ) {
$out = $row['sent'] . " " . $row['received'];
}//end while
}//end if query
return ($out);
}//end function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'Faxusers';
$db = mysql_select_db($dbname);
$sql="select distinct userid from faxuserstable";
if ( $rs = mysql_query($sql) {
while ($row = mysql_fetch_array($rs) ) {
$out = $row['userid'] . ":" . getuserarchive($row['userid']);
}//end while
}//end if query
I'm guessing the switching between databases for each user is causing the slowness. Anyways how i can improve the speed of the processing?
thanks in advance.
You have several problems. First, your function, getUserarchive, pulls back all rows all the time. Looks like you forgot to restrict your SQL to only a specific userid. That's a big cause of your speed issues.
Another option would be to pass in all userids you are interested in. Rewrite the SQL as SELECT sent, received FROM faxarchivetable WHERE userid IN (...), which means you'd have one select to pull back all info from your faxarchivetable, instead of one per each userid.
Finally, if both databases are on the same MySQL server, you could just do a single select to pull in all the information:
SELECT Faxusers.faxuserstable.userid, sent, received FROM Faxusers.faxuserstable JOIN Faxarchive.faxarchivetable ON Faxusers.faxuserstable.userid = Faxarchive.faxarchivetable.userid
Are you aware that you can query tables in separate databases by qualifying the tablename?
For example, I think you can get all your information in a single SQL query like this:
SELECT sent, received
FROM Faxarchive.faxarchivetable
WHERE userid IN ( SELECT DISTINCT userid FROM Faxusers.faxuserstable );
Oh, this is the same point ChrisInEdmonton makes. I didn't notice his answer.

Categories