PDO fetchAll命令中未返回值

时间:2018-01-21 19:21:53

标签: php mysql pdo

我想要检索前四行,第二行是四行,依此类推,直到名为Productos的MySQL表结束。如果我从PHPMyAdmin进行查询,则正确检索值。但是当我尝试从PHP检索它们时,没有检索到任何值。

代码:

$this -> minimo = $_GET["minimo"];
echo "</br>" . $this -> minimo;

$this -> qry = "SELECT nombre,descripcion,precio,foto FROM productos       
LIMIT ?,4";
$this -> sqry = $this -> conexion -> prepare($this -> qry);
$this->sqry->bindParam(1,$this -> minimo,PDO::PARAM_INT);
$this -> sqry -> execute();

echo "</br>"; var_dump($this -> sqry);

$this -> resul = $this -> sqry -> fetchAll();

echo "Resul es " ; var_dump($this -> resul);

运行脚本后,我会看到以下内容:

0

object(PDOStatement)#4 (1) { 
        ["queryString"]=> string(62) "SELECT nombre,descripcion,precio,foto FROM productos LIMIT ?,4" }

Resul es array(0) { } 

我如何追溯价值?

由于

1 个答案:

答案 0 :(得分:3)

因为您正在使用延迟加载,即执行参数

中的数组
$this -> sqry -> execute(array($this -> minimo));

所有参数都被视为字符串,将生成

LIMIT '1', 4

'1'是非法语法

所以你必须指定类似这样的类型

$this->minimo = $_GET["minimo"];
$this->qry = "SELECT nombre,descripcion,precio,foto FROM productos LIMIT ?,4";
$this->sqry = $this->conexion->prepare($this->qry);
$this->sqry->bindParam(1, $this->minimo, PDO::PARAM_INT);
$this->sqry->execute();
$this->resul = $this->sqry->fetchAll();

// now $this->resul should be an array of arrays unless 
// you have set PDO up to return Object by default
// so a simple print_r() should show you whats in the returned data
print_r($this->resul);

或者,您可以关闭模​​拟准备作为连接的一部分,并继续使用延迟加载方法

$this->conexion->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

$this->minimo = $_GET["minimo"];
$this->qry = "SELECT nombre,descripcion,precio,foto FROM productos LIMIT ?,4";
$this->sqry = $this -> conexion -> prepare($this -> qry);
$this->sqry->execute(array($this -> minimo));

$this->resul = $this -> sqry -> fetchAll();
  

如果你只想要前4行,你可以使用LIMIT 4但是添加ORDER BY可能是个好主意,以确保你得到正确的前4行可能是这样LIMIT 4 ORDER BY id 1}}

相关问题