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

后端 未结 3 1556
囚心锁ツ
囚心锁ツ 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();
    

提交回复
热议问题