Doctrine DBAL 准备好的查询
Doctrine DBAL prepared query
我正在使用 PHP 学说 DBAL,我想做的是像这样的 get 方法:
function get($attr, $value){
$conn = DriverManager::getConnection($params, $config);
$sql = "SELECT * FROM mytable WHERE ? = ?";
$statement = $conn->executeQuery($sql, array($attrs, $value));
return $statement->fetchAll();
}
get("id", 1);
但它不起作用。我想知道是否有可能获得列和值的参数化。
这是我正在使用的文档:
http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#executequery
不,这是不可能的。您不能动态绑定列名(这不是 doctrine
/symfony
限制 - 这就是数据库的工作方式)。
准备语句的方式 works:
Prepared statements basically work like this:
- Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters
(labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
- The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it
- Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application
may execute the statement as many times as it wants with different
values
因此,您无法在不知道要转到哪些列的情况下执行第 2 步 "use"。
备选方案:
你想要实现的可以通过首先准备 sql
字符串,然后解析它(准备语句)然后绑定 values
来完成
我正在使用 PHP 学说 DBAL,我想做的是像这样的 get 方法:
function get($attr, $value){
$conn = DriverManager::getConnection($params, $config);
$sql = "SELECT * FROM mytable WHERE ? = ?";
$statement = $conn->executeQuery($sql, array($attrs, $value));
return $statement->fetchAll();
}
get("id", 1);
但它不起作用。我想知道是否有可能获得列和值的参数化。 这是我正在使用的文档: http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#executequery
不,这是不可能的。您不能动态绑定列名(这不是 doctrine
/symfony
限制 - 这就是数据库的工作方式)。
准备语句的方式 works:
Prepared statements basically work like this:
- Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
- The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it
- Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values
因此,您无法在不知道要转到哪些列的情况下执行第 2 步 "use"。
备选方案:
你想要实现的可以通过首先准备 sql
字符串,然后解析它(准备语句)然后绑定 values