我有一个带有函数的类,无论标识列是什么,它都会从数据库中提取任何数据,基本上看起来像这样
use Database\DB;
class General extends DB
{
private $fooBar;
public function getData($column, $table, $value) {
$column = (array) $column;
$column = implode(', ', $column);
$test = $this->query("SELECT `$column` FROM `$table` WHERE $column[0] = :value", array("value" => $value));
}
}
并执行如下:
return $this->general->getData(['name'], 'people', 'John Anderson');
但是,我收到一条错误消息,告诉我一个不存在的列输入值为' n' (这正是列名的第一个字符,无论列名是什么值)
完整错误;
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'n' in 'where clause'' in a\long\path\DB.class.php on line 50
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'n' in 'where clause' in a\long\path\DB.class.php on line 50
提前致谢, 霍尔迪阿
答案 0 :(得分:3)
摆脱界限
$column = implode(', ', $column);
它用一个包含所有以逗号分隔的列名的字符串替换数组。然后$column[0]
将是第一个列名的第一个字符,而不是第一个列名。
答案 1 :(得分:0)
在这里放下你的完整查询..比它更容易!
修改强>
试试这段代码:
dates <- as.Date(demo$date, format = "%m/%d/%Y")
head(dates)
# [1] "2010-12-31" "2013-04-01" "2015-06-02" "2015-06-15" "2015-01-30"
# [6] "2014-04-15"
table(format(dates, format = "%Y"))
#
# 2010 2013 2014 2015
# 1 5 4 8
我更改了以下内容:
use Database\DB;
class General extends DB
{
private $fooBar;
public function getData($column, $table, $value) {
$columns = (array) $column;
$column = implode(', ', $columns);
$test = $this->query("SELECT `$column` FROM `$table` WHERE $columns[0] = :value", array("value" => $value));
}
}
至$column = (array) $column;
并且
$columns = (array) $column;
到
SELECT `$column` FROM `$table` WHERE $column[0] = :value", array("value" => $value)
答案 2 :(得分:0)
这应该解决它(参见@Barmar的回答):
(注意内爆声明的不同之处)。
use Database\DB;
class General extends DB
{
private $fooBar;
public function getData($column, $table, $value) {
$column = (array) $column;
$whereCol = $column[0];
$column = implode('`, `', $column);
$test = $this->query("SELECT `$column` FROM `$table` WHERE $whereCol = :value", array("value" => $value));
return $test;
}
}