php MySQL检查表是否存在而不抛出异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1525784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:56:25  来源:igfitidea点击:

MySQL check if a table exists without throwing an exception

phpmysqlpdodatabase

提问by clops

What is the best way to check if a table exists in MySQL (preferably via PDO in PHP) without throwing an exception. I do not feel like parsing the results of "SHOW TABLES LIKE" et cetera. There must be some sort of boolean query?

在不抛出异常的情况下检查 MySQL 中是否存在表(最好通过 PHP 中的 PDO)的最佳方法是什么。我不想解析“SHOW TABLES LIKE”等的结果。必须有某种布尔查询?

回答by nickf

I don't know the PDO syntax for it, but this seems pretty straight-forward:

我不知道它的 PDO 语法,但这看起来很简单:

$result = mysql_query("SHOW TABLES LIKE 'myTable'");
$tableExists = mysql_num_rows($result) > 0;

回答by Michael Todd

If you're using MySQL 5.0 and later, you could try:

如果您使用的是 MySQL 5.0 及更高版本,您可以尝试:

SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = '[database name]' 
AND table_name = '[table name]';

Any results indicate the table exists.

任何结果都表明该表存在。

From: http://www.electrictoolbox.com/check-if-mysql-table-exists/

来自:http: //www.electrictoolbox.com/check-if-mysql-table-exists/

回答by Falk

Using mysqli i've created following function. Asuming you have an mysqli instance called $con.

使用 mysqli 我创建了以下函数。假设您有一个名为 $con 的 mysqli 实例。

function table_exist($table){
    global $con;
    $table = $con->real_escape_string($table);
    $sql = "show tables like '".$table."'";
    $res = $con->query($sql);
    return ($res->num_rows > 0);
}

Hope it helps.

希望能帮助到你。

Warning:as sugested by @jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $tablevar is clean or even better use parameterised queries.

警告:正如@jcaron 所建议的,此函数可能容易受到 sqlinjection 攻击,因此请确保您的$tablevar 是干净的,甚至更好地使用参数化查询。

回答by Esoterica

This is posted simply if anyone comes looking for this question. Even though its been answered a bit. Some of the replies make it more complex than it needed to be.

如果有人来寻找这个问题,这只是张贴。即使它被回答了一点。一些答复使它比需要的更复杂。

For mysql* I used :

对于 mysql*,我使用了:

if (mysqli_num_rows(
    mysqli_query(
                    $con,"SHOW TABLES LIKE '" . $table . "'")
                ) > 0
        or die ("No table set")
    ){

In PDO I used:

在 PDO 中,我使用了:

if ($con->query(
                   "SHOW TABLES LIKE '" . $table . "'"
               )->rowCount() > 0
        or die("No table set")
   ){

With this I just push the else condition into or. And for my needs I only simply need die. Though you can set or to other things. Some might prefer the if/ else if/else. Which is then to remove or and then supply if/else if/else.

有了这个,我只是将 else 条件推入 or。为了我的需要,我只需要死。虽然你可以设置或其他东西。有些人可能更喜欢 if/else if/else。然后删除或然后提供 if/else if/else。

回答by erandac

Here is the my solution that I prefer when using stored procedures. Custom mysql function for check the table exists in current database.

这是我在使用存储过程时更喜欢的解决方案。用于检查当前数据库中是否存在表的自定义 mysql 函数。

delimiter $$

CREATE FUNCTION TABLE_EXISTS(_table_name VARCHAR(45))
RETURNS BOOLEAN
DETERMINISTIC READS SQL DATA
BEGIN
    DECLARE _exists  TINYINT(1) DEFAULT 0;

    SELECT COUNT(*) INTO _exists
    FROM information_schema.tables 
    WHERE table_schema =  DATABASE()
    AND table_name =  _table_name;

    RETURN _exists;

END$$

SELECT TABLE_EXISTS('you_table_name') as _exists

回答by Martin Lisicki

As a "Show tables" might be slow on larger databases, I recommend using "DESCRIBE " and check if you get true/false as a result

由于“显示表”在较大的数据库上可能会很慢,我建议使用“DESCRIBE”并检查结果是否为真/假

$tableExists = mysqli_query("DESCRIBE `myTable`");

回答by gilcierweb

Zend framework

Zend 框架

public function verifyTablesExists($tablesName)
    {
        $db = $this->getDefaultAdapter();
        $config_db = $db->getConfig();

        $sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}'  AND table_name = '{$tablesName}'";

        $result = $db->fetchRow($sql);
        return $result;

    }

回答by Robin Andrews

If the reason for wanting to do this is is conditional table creation, then 'CREATE TABLE IF NOT EXISTS' seems ideal for the job. Until I discovered this, I used the 'DESCRIBE' method above. More info here: MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

如果想要这样做的原因是有条件的表创建,那么“CREATE TABLE IF NOT EXISTS”似乎是这项工作的理想选择。在我发现这一点之前,我使用了上面的“DESCRIBE”方法。更多信息:MySQL“如果不存在则创建表”-> 错误 1050

回答by Namkeen Butter

$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
    foreach( $row as $key => $value )
    {
        if ( $value = BTABLE )  // BTABLE IS A DEFINED NAME OF TABLE
            echo "exist";
        else
            echo "not exist";
    }
}

回答by Hamed

Why you make it so hard to understand?

你为什么这么难理解?

function table_exist($table){ 
    $pTableExist = mysql_query("show tables like '".$table."'");
    if ($rTableExist = mysql_fetch_array($pTableExist)) {
        return "Yes";
    }else{
        return "No";
    }
}