检查列是否存在,如果不存在,通过PHP添加MySQL [英] Check if column exists, if not, add in MySQL through PHP

查看:126
本文介绍了检查列是否存在,如果不存在,通过PHP添加MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码检查列是否存在,如果不存在,请添加:

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 table $table add $column varchar (20)");

但是数据库没有变化。有什么建议吗?

But there's no change in the database. Any suggestions why?

数据库已连接。

推荐答案

可以将SQL更改为...

You can change your SQL to...

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

而是使用PHP PDO或MySQLi with prepared语句。

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

MySQLi解决方案

$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();

这篇关于检查列是否存在,如果不存在,通过PHP添加MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆