如何使用PHP,PDO,MySQL检查列是否不存在? [英] How to check if column does not exist using PHP, PDO, MySQL?
问题描述
在我的应用程序中,我有一个适用于多个用户的通用查询.在某些情况下,用户之间的表结构可能会有所不同.我有一个查询,我只想将其应用于表中存在该列的用户.
In my application I have a generic query that applies to multiple users. There are instances where the table structure may differ between users. I have a query that I only want to apply to the users where the column exists in their table.
function get_item($user_id) {
global $dbh;
$sth = $dbh->query ("SELECT item_type FROM items WHERE user_id = '$user_id'");
$row = $sth->fetch();
$item_type = $row['item_type'];
return $item_type;
}
如果我的表中不存在"item_type"列,我想忽略它,并将$ item_type变量设置为NULL.
If the column 'item_type' does not exist in my table, I want to ignore it, and set the $item_type variable to NULL.
对于这些用户,我在代码查询行上遇到了错误:
For these users, I am getting the error on the query line of code:
致命错误:带有消息的未捕获异常'PDOException' 'SQLSTATE [42S22]:找不到列:1054中的未知列'item_type' /item_display.php:5中的字段列表"
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'item_type' in 'field list' in /item_display.php:5
有什么想法吗?
推荐答案
我不知道它是否对您有帮助,但是您可以尝试以下方法:
I don't know if it helps you, but you can try this:
if (count($dbh->query("SHOW COLUMNS FROM `items` LIKE 'item_type'")->fetchAll())) {
$sth = $dbh->query ("SELECT item_type FROM items WHERE user_id = '$user_id'");
$row = $sth->fetch();
$item_type = $row['item_type'];
} else {
$item_type = null;
}
它检查该列是否存在并执行任务.
It checks if the column exists and performs the task.
这篇关于如何使用PHP,PDO,MySQL检查列是否不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!