There are two functions below the first one let you check if a column in a database table exists which requires two arguments. Table name and column name.
function if_column_exists( $table, $column ) {
global $db;
if ( empty ( $table ) || empty ( $column ) ) {
return FALSE;
}
if ( $result = $db->query( "SHOW COLUMNS FROM $table LIKE '$column'" ) ) {
if ( $result->num_rows == 0 ) {
return FALSE;
} else {
return TRUE;
}
}
}
To use the above function you have to call it by passing table name and column name like below.
if ( if_column_exists( 'accounts', 'group_id' ) == FALSE ) {
$query = "ALTER TABLE `accounts` ADD `group_id` bigint(20) NULL AFTER `memo`";
$result = $db->query($query) or die($db->error);
}
The next function helps you to identify if a table exists or not and accepts the argument table name only.
function if_table_exists( $tablename ) {
global $db;
if ( empty( $tablename ) ) {
return FALSE;
}
if($result = $db->query("SHOW TABLES LIKE '$tablename'")) {
if($result->num_rows == 0) {
return FALSE;
} else {
return TRUE;
}
}
}
To call it use the following method with single table name argument.
if ( if_table_exists("messages") == FALSE ) {
$query = 'CREATE TABLE `messages` (
`message_id` bigint(20) NOT NULL AUTO_INCREMENT,
`message_datetime` datetime NOT NULL,
`message_detail` varchar(1000) NULL,
PRIMARY KEY (`message_id`)
)';
$result = $db->query($query) or die($db->error);
echo 'Messages Table created.<br>';
}
Please note that you are passing global object of database as $db in the function so make sure its replaced with your database object or as below.
define ("DB_HOST", "localhost"); //Databse Host.
define ("DB_USER", "root"); //Databse User.
define ("DB_PASS", ""); //database password.
define ("DB_NAME", "general_ledger"); //database Name.
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}