检查MySQL表是否存在 [英] Check if MySQL table exists or not

查看:100
本文介绍了检查MySQL表是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
MySQL检查表是否存在而不会引发异常

Possible Duplicate:
MySQL check if a table exists without throwing an exception

我的项目中有一个动态mysql查询生成器,可从不同的表创建选择查询.
我需要检查当前处理表是否存在.
假设我的表是table1,table2和table3.我的代码是这样的:

I have a dynamic mysql query builder in my project that creates select queries from different tables.
I need to check if the current processing table exists or not.
Imagine that my tables are table1, table2, and table3. My code is something like this:

<?php
for($i = 1 ; $i <= 3 ; $i++) {
   $this_table = 'table'.$i;
   $query = mysql_query("SELECT * FROM $this_table");
   // ...
}
?>

我该如何进行检查(请告诉我最简单的方法).

How can I do this check (Please tell me the simplest way).

推荐答案

更新的mysqli版本:

Updated mysqli version:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
    if($result->num_rows == 1) {
        echo "Table exists";
    }
}
else {
    echo "Table does not exist";
}

原始mysql版本:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists";
else echo "Table does not exist";

参考 PHP文档.

这篇关于检查MySQL表是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆