简体   繁体   中英

How to know if a name refers to mysql table or mysql view in a php script

I can select all tables in a database like this

$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
  $tables[] = $row[0];
}

And following code populate $return variable which can be used to backup the database.

  foreach($tables as $table)
  {
    $result = mysql_query('SELECT * FROM '.$table);
    $num_fields = mysql_num_fields($result);

    $return.= 'DROP TABLE IF EXISTS '.$table.';';
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
    $return.= "\n\n".$row2[1].";\n\n";

    for ($i = 0; $i < $num_fields; $i++) 
    {
      while($row = mysql_fetch_row($result))
      {
        $return.= 'INSERT INTO '.$table.' VALUES(';
        for($j=0; $j<$num_fields; $j++) 
        {
          $row[$j] = addslashes($row[$j]);
          $row[$j] = ereg_replace("\n","\\n",$row[$j]);
          if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
          if ($j<($num_fields-1)) { $return.= ','; }
        }
        $return.= ");\n";
      }
    }
    $return.="\n\n\n";
  } 

My database has two mysql views. Above code generates "INSERT INTO...." string even for mysql views which I need to avoid. So before starting the 'for loop' to generate "INSERT INTO.." values I need to check if $table is actually a mysql table or view. How to identify whether a name refers to mysql table or mysql view?

SHOW [FULL] TABLES

The FULL modifier is supported such that SHOW FULL TABLES displays a second output column. Values for the second column are BASE TABLE for a table and VIEW for a view.

您可以使用命令SHOW FULL TABLES ,它将添加第二列,显示关系是BASE TABLE还是VIEW

If I understand you correctly, you want to know how to detect whether a table/view exists. If so, the following should help. I have written a wrapper class for PDO and this statement has been taken from the tables_exists() method:

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = :database AND TABLE_NAME = :table

The above query can be altered very easily to determine whether a view exists as well.

Additional Note

Please do not use the mysql_* API as these functions are now deprecated. Instead, you should use either PDO or mysqli. See the following links:

  1. PDO
  2. MySQLi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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