PHP:简单的PDO循环不起作用?

时间:2017-12-01 13:41:17

标签: php mysql pdo

只是解析文件并构建查询但是$row只返回 一个 结果,其中is hold得到每个查询的结果。< / p>

while (!feof($f)) {

    $contents = '';
    $contents = fgets($f);
    $p = explode(" ", $contents);

    $req = "SELECT id_product from ps_product WHERE `reference`='".$p[1]."'";


    $rs = $dbh->prepare($req);
    $rs->execute();

    $row  = $rs->fetch();

    print_r($row);
}

我最后只得到一个结果

我的调试是这样的:

M0852 

PDOStatement Object ( [queryString] => SELECT id_product from ps_product WHERE `reference`='M0852 ' ) 

M0850 

PDOStatement Object ( [queryString] => SELECT id_product from ps_product WHERE `reference`='M0850 ' ) 

M0850 

PDOStatement Object ( [queryString] => SELECT id_product from ps_product WHERE `reference`='M0850 ' ) 

M0851 

PDOStatement Object ( [queryString] => SELECT id_product from ps_product WHERE `reference`='M0851 ' ) 

M0851 

PDOStatement Object ( [queryString] => SELECT id_product from ps_product WHERE `reference`='M0851 ' ) 

M0855 

PDOStatement Object ( [queryString] => SELECT id_product from ps_product WHERE `reference`='M0855 ' ) 

M0849 

PDOStatement Object ( [queryString] => SELECT id_product from ps_product WHERE `reference`='M0849 ' ) 
  

数组([id_product] =&gt; 2662 [0] =&gt; 2662)

当我希望每个查询得到一个包含结果的数组时。

1 个答案:

答案 0 :(得分:2)

只有文件中的最后一行最后没有LF字符 使用trim()将其剥离

$req = "SELECT id_product from ps_product WHERE `reference`=?";
$rs = $dbh->prepare($req);
while (!feof($f)) {

    $contents = trim(fgets($f));
    $p = explode(" ", $contents);

    $rs->execute([$p[1]]);
    $row  = $rs->fetch();

    print_r($row);
}