Check if a table exists in the database

22

How to check if a table exists in the database before attempting to use it?

<?php
// define a tabela
$table = 'banana';

// verificar se tabela "banana" existe aqui
// $tableExists = ??

// executa consulta se existir
if ($tableExists) {
  $query = 'SELECT * FROM '.$table.' WHERE 1';
  // executa a consulta, etc...
} else {
  die ('A tabela '.$table.' não foi encontrada na base de dados!');
}
?>
    
asked by anonymous 16.01.2014 / 14:11

3 answers

20

Based on in this SO response , the simplest form is:

$table = 'banana';
$tableExists = $db->query("SHOW TABLES LIKE '$table'")->rowCount() > 0;

Alternatively, if someone does not want to use PDO:

$table = 'banana';
$result = mysqli_query("SHOW TABLES LIKE '$table'");
$tableExists = $result && $result->num_rows > 0;
    
16.01.2014 / 14:29
8

By information_schema of mysql it is possible to access all the tables of a database:

SELECT table_name FROM information_schema.tables WHERE table_schema = 'data_base'
AND table_name = 'nome_da_tabela'

After the query, use the function / method of the bank driver that retries the amount of bank records:

count () (generically)

rowCount () (PDO)

mysqli_num_rows () (mysqli)

$db = new PDO('mysql:host=localhost dbname=test','usuario', 'senha');
$sql = 'SELECT table_name FROM information_schema.tables WHERE table_schema = :database
AND table_name = :tabela';

$stmt = $db->prepare($sql);
$stmt->bindValue(':database', 'test';
$stmt->bindValue(':tabele', 'bananas';
$stmt->execute();
$tabelas = $stmt->rowCount();

if($tabelas >= 1 ){
  echo 'tabela valida';
  //efetuar select
}else{
  echo 'tabela invalida';
  //efetuar um create table?
}

about information_schema

    
16.01.2014 / 14:17
7

Create a function so you can dynamically search:

public function verificaTabela($tabela)
{
    $tabelas_consulta = mysql_query('SHOW TABLES');

    while ($tabelas_linha = mysql_fetch_row($tabelas_consulta))
    {
        $tabelas[] = $tabelas_linha[0];
    }

    if (!in_array($tabela, $tabelas)) 
    {
        return false;
    }
    else
    {
        return true;
    }
}

$tabela_existe = verificaTabela('minha_tabela');
    
16.01.2014 / 14:21