Home >php教程 >PHP源码 >判断表是否存在

判断表是否存在

PHP中文网
PHP中文网Original
2016-05-25 17:14:441084browse

判断表是否存在

<?php
//方法一
    mysql_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;2260375&#39;) or die(&#39;can\&#39;t not connect database&#39;);
    if((int)check_table_is_exist(&#39;show databases;&#39;,&#39;test&#39;)==1)
    {
        echo &#39;该表存在&#39;;
    }
    else 
    {
        echo &#39;该表不存在&#39;;
    }
    function check_table_is_exist($sql,$find_table)
    {
        $row=mysql_query($sql);
        $database=array();
        $finddatabase=$find_table;
        while ($result=mysql_fetch_array($row,MYSQL_ASSOC))
        {
            $database[]=$result[&#39;Database&#39;];
        }
        unset($result,$row);
        mysql_close();
        
        /*开始判断表是否存在*/
        if(in_array($find_table,$database))
        {
            return true;
        }
        else 
        {
            return false;
        }
    }
    


//////////////////////////////////////////////方法二
    mysql_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;root&#39;);         
    $result = mysql_list_tables(&#39;database&#39;);          
    $i=0; 
    while($i<mysql_num_rows($result))
    {
    if (&#39;Table_Name&#39; == mysql_tablename($result,$i)) {
        echo &#39;存在&#39;;
            break;
    }                          
        $i++;     
    }
    echo &#39;不存在&#39;;
mysql_close();

//////////////////////////////////////方法三
$data   = array();
$dbname = &#39;你要查询的表名&#39;;

mysql_connect(&#39;localhost&#39;, &#39;root&#39;, &#39;&#39;) or die(&#39;Cann\&#39;t connect server!&#39;);
$result = mysql_query(&#39;show databases;&#39;);
While($row = mysql_fetch_assoc($result)){
    $data[] = $row[&#39;Database&#39;];
}unset($result, $row);

mysql_close();

print_r($data);

if (in_array(strtolower($dbname), $data))
    die(&#39;存在&#39;);
else
    die(&#39;不存在&#39;);
?>

以上就是判断表是否存在的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn