Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save michmzr/d96358a7866f2eeacb5793c2acfb9e07 to your computer and use it in GitHub Desktop.

Select an option

Save michmzr/d96358a7866f2eeacb5793c2acfb9e07 to your computer and use it in GitHub Desktop.
A function for WordPress to check if a column exists in a database table or not. Returns true if a database table column exists. Otherwise returns false.
<?php
/**
* Returns true if a database table column exists. Otherwise returns false.
*
* @link http://stackoverflow.com/a/5943905/2489248
* @global wpdb $wpdb
*
* @param string $table_name Name of table we will check for column existence.
* @param string $column_name Name of column we are checking for.
*
* @return boolean True if column exists. Else returns false.
*/
function mycode_table_column_exists( $table_name, $column_name ) {
global $wpdb;
$column = $wpdb->get_results( $wpdb->prepare(
"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s ",
DB_NAME, $table_name, $column_name
) );
if ( ! empty( $column ) ) {
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment