direxit
direxit

Reputation: 405

PHP: Simple PDO loop not working?

Just parsing a file and building a query BUT the $row only returns me one result, where is hold get A result per query i make.

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);
}

I am only getting one result at the end

My debug is like this :

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 ' ) 

Array ( [id_product] => 2662 [0] => 2662 )

when I am expecting to get one array with results per query.

Upvotes: 0

Views: 60

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157839

only the last line in the file don't have a LF character at the end.
use trim() to strip it out

$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);
}

Upvotes: 2

Related Questions