mysql判斷是否存在表

1、在Yii2框架中判斷數據表是否存在。

private static function checkTable($table){
    $sql = "SHOW TABLES LIKE '". $table."'";
    $existTable = static::findBySql($sql)->asArray()->one();
    if(empty($existTable)){
        return 0;
    }
    return 1;
}

2、在php中判斷數據表是否存在。

<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'root';
$password = '';
try {
  $pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
  die("數據庫連接失敗".$e->getMessage());
}
$table = 'cy_news';
//判斷表是否存在
$result = $pdo->query("SHOW TABLES LIKE '". $table."'");
$row = $result->fetchAll();
if('1' == count($row)){
  echo "Table exists";
} else {
  echo "Table does not exist";
}
?>
$con = mysql_connect("localhost","root","");
mysql_select_db("php_cms", $con);
$table = 'cy_news';
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '". $table."'"))==1) {
  echo "Table exists";
} else {
  echo "Table does not exist";
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章