如何遍历特定的列名并在PHP / MySQL中清除这些字段?

时间:2012-10-28 13:26:16

标签: mysql foreach pdo fatal-error

我正在尝试执行PHP / MySQL查询以选择一组列并清除特定记录的字段:

$sth = $dbh->query("SELECT column_name
                    FROM information_schema.columns
                    WHERE table_name = 'users'
                    AND column_name like '%_abc'");

$rows = $sth->fetchAll();

foreach ($rows as $row){

    $sth = $dbh->prepare("UPDATE users
                          SET $row = NULL
                          WHERE user_id = $user_id");

    $sth->execute();        

}

但是,我收到以下错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: 
Column not found: 1054 Unknown column 'Array' in 'field list'

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

代替 "UPDATE users SET $row = NULL WHERE user_id = $user_id"

尝试"UPDATE users SET {$row['column_name']} = NULL WHERE user_id = $user_id"

答案 1 :(得分:1)

您的$row是一个数组。尝试

foreach ($rows as $id => $value {
   ... SET $value = NULL ...
}

您可以使用

查看$row
var_dump($row);

答案 2 :(得分:0)

$row是一个数组。要从所选行访问特定字段,请使用$row['column_name']