Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

Aus PHP prüfen, ob eine Spalte in einer MySQL-Tabelle existiert

Frage den Server, welche Spalten er hat:

$result = mysql_query("SHOW COLUMNS FROM `table` LIKE 'fieldname'"); $exists = (mysql_num_rows($result))?TRUE:FALSE; if($exists) { // do your stuff } 

Wenn das LIKE-Muster etwas matcht, ist die Spalte vorhanden – andernfalls nicht.

Weiterführend: MySQL, Check if a column exists in a table with SQL

Beachte, dass mysql_* veraltet und entfernt ist – nutze mysqli oder PDO.

Zwei Alternativen sind oft besser. Ein SELECT ... LIMIT 1 in einem try-Block wirft eine Exception, wenn die Spalte fehlt – das passt zu bequemen Existenzprüfungen. Oder frage information_schema.columns mit einem Filter WHERE table_schema = ? AND table_name = ? AND column_name = ? ab; das vermeidet die Platzhalter-Semantik von LIKE und ist vorzuziehen, weil % und _ in einem Spaltennamen sonst als Wildcards behandelt würden.