简体   繁体   中英

Rename mysql table if exist if not create a new one

Currently I'm trying to create a new table using mysqli. If the table 'default' exist rename it as the current date and time and if not exist create a new table called default.I get date and time from a previous php page that contains current date and time in plain text without / , - , :. How can I do it using mysqli ?

$bk_time=$_POST['system_clock']."backup";
$conn = new mysqli($db_hostname, $db_username, $db_password);
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}
//check default exist
$sql = "SHOW TABLES FROM `descript`.`default`;";
if ($conn->query($sql) === TRUE) {

  $sql. = 'RENAME TABLE `default` TO `$bk_time`';
  echo 'exist';
}
else {
 echo 'not exist ';
 $sql. = 'CREATE TABLE `descript`.`default`';
}
mysqli_autocommit($conn, false);
mysqli_query($conn, $sql);

I suggest using stored procedures:

  1. To check if table exists
  2. To rename table

The first one would be something like the following

IF EXISTS (
(SELECT * FROM information_schema.TABLES
    WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = _tableName))
    THEN SET _result = 0;
ELSE
    SET _result = 1;
END IF;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM