MySQL comprueba si existe una tabla sin lanzar una excepción


Cuál es la mejor manera de comprobar si existe una tabla en MySQL (preferiblemente a través de PDO en PHP) sin lanzar una excepción. No tengo ganas de analizar los resultados de "MOSTRAR TABLAS COMO" etcétera. Debe haber algún tipo de consulta booleana?

Author: clops, 2009-10-06

10 answers

No conozco la sintaxis de PDO para ello, pero esto parece bastante sencillo:

$result = mysql_query("SHOW TABLES LIKE 'myTable'");
$tableExists = mysql_num_rows($result) > 0;
 197
Author: nickf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-06 14:04:13

Si estás usando MySQL 5.0 y versiones posteriores, puedes probar:

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

Cualquier resultado indica que la tabla existe.

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

 39
Author: Michael Todd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-06 14:03:49

Usando mysqli he creado la siguiente función. Suponiendo que tiene una instancia de mysqli llamada {con.

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

Espero que ayude.

Advertencia: como sugiere @jcaron, esta función podría ser vulnerable a ataques sqlinjection, así que asegúrese de que su $table var esté limpio o incluso use mejor las consultas parametrizadas.

 8
Author: Falk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-31 12:15:23

Aquí está la solución my que prefiero cuando uso procedimientos almacenados. Función mysql personalizada para comprobar que la tabla existe en la base de datos actual.

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
 4
Author: erandac,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-10 06:15:23

Esto se publica simplemente si alguien viene buscando esta pregunta. Aunque ha sido contestada un poco. Algunas de las respuestas lo hacen más complejo de lo necesario.

Para mysql * Utilicé:

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

En la DOP utilicé:

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

Con esto solo empuje la condición else en o. Y para mis necesidades solo necesito morir. Aunque se puede establecer o a otras cosas. Algunos podrían preferir el if / else if / else. Que es entonces eliminar o y luego suministrar si / else si / else.

 4
Author: Esoterica,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-19 17:04:04

Como " Mostrar tablas "puede ser lento en bases de datos más grandes, recomiendo usar "DESCRIBIR" y verificar si obtiene verdadero/falso como resultado

$tableExists = mysqli_query("DESCRIBE `myTable`");
 2
Author: Martin Lisicki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-29 07:22:08
$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";
    }
}
 0
Author: Namkeen Butter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-18 14:33:19

Zend framework

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;

    }
 -1
Author: gilcierweb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-18 16:56:05

Si la razón para querer hacer esto es la creación de tabla condicional, entonces 'CREAR TABLA SI NO EXISTE' parece ideal para el trabajo. Hasta que descubrí esto, utilicé el método de "DESCRIBIR" anterior. Más información aquí: MySQL "CREAR TABLA SI NO EXISTE" - > Error 1050

 -1
Author: Robin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:03:01

¿Por qué lo haces tan difícil de entender?

function table_exist($table){ 
    $pTableExist = mysql_query("show tables like '".$table."'");
    if ($rTableExist = mysql_fetch_array($pTableExist)) {
        return "Yes";
    }else{
        return "No";
    }
} 
 -8
Author: Hamed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-24 05:20:53