本文介绍了[zend][db] fetchAll 多变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对具有 2 个变量的查询使用 fetchAll.我无法弄清楚语法.我只能用 1 个变量进行管理:

I'm trying to use fetchAll on a query that has 2 variables. I can't figure out the syntax.I can manage with only 1 variable:

$sql = "SELECT * FROM mytable WHERE field1 = ?";
$this->_db->fetchAll($sql,$value1);  # that works

但是当查询有多个变量时我遇到了一些问题

However I'm having some issues when query has multiple variables

$sql = "SELECT * FROM mytable WHERE field1 = ? AND field2 = ?";
$this->_db->fetchAll($sql,$value1,$value2); # doesn't work
$this->_db->fetchAll($sql,array("field1"=>$value1,"field2"=>$value2)); # doesn't work either

我想使用的原因?不是将变量直接放入查询中,而是我了解到使用 ?允许由数据库引擎对查询进行通用编译并提高性能.

The reason why I want to use ? instead of placing the variables directly into the query is that I've learned that using ? allows for the query to be compiled generically by the db engine and improves performances.

推荐答案

有两种类型的参数,named 参数和 positional 参数.你正在混合这两种类型,这是行不通的.

There are two types of parameter, named parameters and positional parameters. You're mixing the two types and that won't work.

命名参数按名称匹配占位符.名称以 : 符号开头.参数名称与您碰巧使用它们的列名称不同.您在关联数组中提供参数值,使用参数名称(而不是列名称)作为数组键.例如:

Named parameters match a placeholder by name. Names are started with the : symbol. The parameter names are not the same as the names of the columns you happen to use them for. You supply parameter values in an associative array, using the parameter name (not the column name) as the array keys. For example:

$sql = "SELECT * FROM mytable WHERE field1 = :param1 AND field2 = :param2";
$this->_db->fetchAll($sql,array("param1"=>$value1,"param2"=>$value2));

位置参数使用 ? 符号作为占位符.您使用简单(非关联)数组提供参数值,并且数组中值的顺序必须与查询中参数占位符的顺序匹配.例如:

Positional parameters use the ? symbol for the placeholder. You supply parameter values using a simple (non-associative) array, and the order of values in the array must match the order of parameter placeholders in your query. For example:

$sql = "SELECT * FROM mytable WHERE field1 = ? AND field2 = ?";
$this->_db->fetchAll($sql,array($value1,$value2));

大多数品牌的 SQL 数据库本身只支持一种风格或另一种风格,但 PDO 尝试支持这两种风格,如果需要,在准备查询之前重写 SQL.由于 Zend_Db 是仿照 PDO 建模的,因此 Zend_Db 也支持这两种参数样式.

Most brands of SQL database natively support only one style or the other, but PDO attempts to support both, by rewriting the SQL if necessary before preparing the query. Since Zend_Db is modeled after PDO, Zend_Db also supports both parameter styles.

这篇关于[zend][db] fetchAll 多变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 19:26
查看更多