Check if column exists, if not, add in MySQL through PHP

后端 未结 3 1543
囚心锁ツ
囚心锁ツ 2020-12-20 09:07

I\'m using the following code to check if the column exists, and if it doesn\'t, add it:

mysql_query(\"select $column from $table\") or mysql_query(\"alter t         


        
相关标签:
3条回答
  • 2020-12-20 09:28

    You can change your SQL to...

    //THIS IS BETTER BUT DONT USE THIS
    $qry = "ALTER IGNORE TABLE {$table} ADD {$column} VARCHAR(20);"
    

    Instead use PHP PDO or MySQLi with prepared statements. Instead of that legacy horror with concatinated unescaped strings.

    MySQLi Solution:

    $mysqli = new mysqli($cfg->host, $cfg->user, $cfg->password, $cfg->db);
    
    if ($mysqli->connect_errno) {
        echo 'Connect failed: ', $mysqli->connect_error, '" }';
        exit();
    }
    
    if ($stmt = $mysqli->prepare("ALTER IGNORE TABLE ? ADD ? VARCHAR(20);")) {
        $stmt->bind_param("ss", $table, $column);
        $stmt->execute();
        $stmt->close();
    }
    $mysqli->close();
    
    0 讨论(0)
  • 2020-12-20 09:44

    For msqli users

    $result = $mysqli->query("SHOW COLUMNS FROM tablename LIKE 'keyword");
    $exists = (mysqli_num_rows($result))?TRUE:FALSE;
    
    0 讨论(0)
  • 2020-12-20 09:53
    $r=mysql_num_rows(mysql_query("SHOW columns from '".$table."' where field='".$column."'"));
    if ($r==0){
        mysql_query("alter table $table add $column varchar (20)");
    }
    
    0 讨论(0)
提交回复
热议问题