Reputation: 6205
I would like to scrap all my records in a database. I want to use just a PHP script, not PhpMyAdmin. I have will be using a MySQL database administrator account. What SQL query should I use?
Upvotes: 0
Views: 31161
Reputation: 10643
To completely empty the database, dropping all tables (if that's what you really want to do), run this PHP script.
<?php
header('Content-Type: text/plain');
$link = mysqli_connect('host', 'username', 'password');
mysqli_select_db($link, 'database_name');
mysqli_set_charset($link, 'utf8');
$sql = 'SHOW TABLE STATUS FROM `database_name`;';
$result = mysqli_query($link, $sql);
$rows = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
$n = 0;
foreach ($rows as $row) {
$sql = 'DROP TABLE IF EXISTS `' . mysql_real_escape_string($row['Name']) . '`;';
mysqli_query($link, $sql);
++$n;
}
echo $n . 'tables dropped' . PHP_EOL;
exit(__FILE__ . ': ' . __LINE__);
Upvotes: 3
Reputation: 268344
You could run a query:
/* Assumes the existence of a few key variables
and further, that your user has the appropriate permissions */
mysql_connect( $host, $user, $pass ) or die( mysql_error() );
mysql_select_db( $db ) or die( mysql_error() );
mysql_query( "TRUNCATE TABLE tablename" );
Or
mysql_query( "DELETE FROM tablename" );
These queries will result in all records being deleted. If you want only certain records to be dropped, add a where
clause:
mysql_query( "DELETE FROM tablename WHERE userid = 5" );
Upvotes: 12