I am trying to add a column by checking if it exists. If not it should give message that it already exists with the code below.
$prefix = 'vm_';
$col_name = 'checking';
$col = "SELECT ".$col_name." FROM ".$prefix."users";
if (!$col){
$insert_col = "ALTER TABLE ".$table." ADD ".$col_name." DATETIME NOT NULL";
mysql_query($insert_col);
echo $col_name.' has been added to the database';
} else {
echo $col_name.' is already exists';
}
But it doesn't add any column and directly displays message that the column already exists.
You never execute your query, your condition is instead your query string:
if (!$col) { //always false, since a nonempty string is always truthy
Here is the final code. There was stupid mistake; I didn't use mysql_query
for $col
$prefix = 'vm_';
$col_name = 'checking';
$col = mysql_query("SELECT ".$col_name." FROM ".$prefix."users");
if (!$col){
//$insert_col = "ALTER TABLE ".$table." ADD ".$col_name." DATETIME NOT NULL";
mysql_query("ALTER TABLE ".$prefix."users ADD ".$col_name." DATETIME NOT NULL");
echo $col_name.' has been added to the database';
} else {
echo $col_name.' is already exists';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With