2013-08-05 12 views
7

Sto provando a verificare se esiste una tabella e, in tal caso, fare alcune azioni. Continuo a ricevere un errore che mi dice che il tavolo non esiste piuttosto che completare il mio assegno. Ecco il codice:Verificare che esista una tabella su MySQL

$tableExists = $db->prepare("SHOW TABLES LIKE $table_array"); 
$tableExists->execute(); 
if($tableExists->rowCount() > 0) { 
    // do some code 
} else { 
    echo "Unable to add because table does not exists"; 
} 

UPDATE: Per suggerimenti qui sotto, io ora faccio la seguente:

$tableExists = $db->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?"); 
$tableExists->execute(array($table_array)); 
if(!is_null($tableExist)) { 
    //do something 
} else { 
    echo "table does not exist; 
} 

Tuttavia, l'istruzione if non sembra funzionare per determinare se la tabella esiste o no . Cos'altro potrei fare?

risposta

10

Provare a utilizzare il information_schema per chiedere se la tabella esiste. Qualcosa di simile

SELECT 
    * 
FROM 
    information_schema 
WHERE TABLE_NAME = "$table_array" 

Date uno sguardo attraverso tutto ciò che la information_schema stive, sarete piacevolmente sorpresi dalle informazioni che ha memorizzato sui database :)

+1

Che ... è ... Impressionante ... E dire che ho preso quel tavolo come parte dei tavoli intrusivi phpMyAdmin ... :) – Salketer

+0

così "aprove" che rispondono ... – jaczes

+0

Mi chiamo Alfred Salketer Arengard (Sì, lo so ...), e io "approvo" questa risposta ... @jaczes;) – Salketer

1
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists"; 
else echo "Table does not exist"; 

ref: check if MySQL table exists or not

+0

Grazie, ho cercato e non avevo trovato quell'altra risposta – Danconia

+0

Perché tutti quei voti negativi? Risolve il problema ... No? – Salketer

+0

sai come posso verificare se la tabella esiste dato l'aggiornamento sopra? – Danconia

0

provate questo:

selezionare caso in cui (selezionare count (*) da INFORMATION_SCHEMA.TABLES dove TABLE_NAME = 'uffici') = 1 allora 'esiste' altro 'non esiste' finiscono

+0

Ciao, potresti spiegarlo di nuovo? Questo è quello che ho adesso, ma non so come testare se il risultato per la query è valido (esiste una tabella) oppure no. $ tableExists = $ db-> prepare ("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =?"); $ TableExists-> execute (array ($ table_array)); if (! is_null ($ tableExist)) {// do code} – Danconia

-1

Prova questa:

select * from table_schema //this is your database name  
where table_name // your table name  
= '$table_array' 

Spero che questo funzioni per voi.

Problemi correlati