Home >Backend Development >PHP Tutorial >How to use php to operate the database to determine whether the table exists

How to use php to operate the database to determine whether the table exists

墨辰丷
墨辰丷Original
2018-06-09 16:29:565454browse

This article mainly introduces the method of using PHP to determine whether a table exists in the database. Interested friends can refer to it. I hope it will be helpful to everyone.

The example of this article describes the method of determining whether a table exists in PHP. The details are as follows:

<?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;);
?>

Summary: The above is the entire content of this article. I hope it can be useful for everyone's learning. help.

Related recommendations:

Use curl to fake IP function in PHP

php uses MagickWand How to add watermark to module operation pictures

php judgment on the current encoding and corresponding coding conversion implementation skills

The above is the detailed content of How to use php to operate the database to determine whether the table exists. For more information, please follow other related articles on the PHP Chinese website!

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