简体   繁体   English

MySQL检查表是否已经存在

[英]MySQL check if table already exists

I have couple of tables in my MySQL database. 我的MySQL数据库中有几个表。 They have a certain naming convention such as. 它们具有某种命名约定,例如。

tbl_1_alpha
tbl_1_beta
tbl_1_alpha2
tbl_2_beta
tbl_3_alpha2

Now I want to check wether a given table is already exists in the database. 现在,我想检查数据库中是否存在给定的表。

eg. 例如。

  • $name = 'tbl_1_alpha' -> exists $name = 'tbl_1_alpha' ->存在
  • $name = 'tbl_1_alpha2' -> exists $name = 'tbl_1_alpha2' ->存在
  • $name = 'tbl_1_alpha3' -> does not exists $name = 'tbl_1_alpha3' ->不存在

To get the result I used the following functions 为了得到结果,我使用了以下功能

 public function exists($name)
    {

        $query = "SHOW TABLES LIKE '$name%'";

        $result = $this->db->query($query);

        if ($result->num_rows() > 0) {
            return true;
        }
        return false;

    }

for a given $name = tbl_1_alpha it return true . 对于给定的$name = tbl_1_alpha它返回true But When I delete the table tbl_1_alpha it still returns true because it matches the name to tbl_1_alpha2 . 但是,当我删除表tbl_1_alpha它仍然返回true因为它将名称与tbl_1_alpha2匹配。 How can I avoid that? 我该如何避免呢?

Can anyone help me to match the exact table name and figure out wether it is already exist or not? 谁能帮我匹配确切的表名,弄清楚它是否已经存在?

No need of query. 无需查询。 just run this 只是运行这个

$this->db->table_exists('customer');

Table Data 表数据


Example

$query = $this->db->table_exists('customer');
$count = count($query);

if (empty($count)) {
    echo "No Table Found";
}
elseif ($count == 1) {
    echo "Oopzz! There is table";
}
elseif ($count >1) {
    echo "Ohh !! There are many tables";
}

You should just remove the wild card from the query. 您应该只从查询中删除通配符。 ie

$query = "SHOW TABLES LIKE '$name'";

Given, of course, that it's not a requirement. 当然,这不是必须的。

Without LIKE : 没有LIKE

Fair enough if you don't want to use the LIKE clause, here's the query without it. 如果您不想使用LIKE子句,这很公平,这是没有它的查询。 It either returns 1 or 0 depending on whether the table exists or not. 根据表是否存在,它返回10

SELECT count((1)) as `ct`  FROM INFORMATION_SCHEMA.TABLES where table_schema ='database' and table_name='table';

And there are many other ways too which are already answered. 而且还有许多其他方法已经得到解决。 Checkout them here : How can I check if a MySQL table exists with PHP? 在此处检出它们: 如何检查MySQL表是否与PHP一起存在?

$check_exists = mysql_query("SHOW TABLES LIKE '$name'");
$table_exists = mysql_num_rows($check_exists) > 0;
if ($table_exists) {
    echo 'table exists';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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