Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL: Insert column if not exists

Tags:

php

mysql

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.

like image 797
Code Lover Avatar asked Nov 30 '22 22:11

Code Lover


2 Answers

You never execute your query, your condition is instead your query string:

if (!$col) { //always false, since a nonempty string is always truthy
like image 178
Asad Saeeduddin Avatar answered Dec 04 '22 03:12

Asad Saeeduddin


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';
}
like image 23
Code Lover Avatar answered Dec 04 '22 02:12

Code Lover