0

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.

5
  • This is the wrong way to do it. By using string concatenation, you are completely bypassing the usefulness of prepared statements. Commented Dec 1, 2017 at 13:44
  • @GrumpyCrouton i understand but i made this with "conventional" bindings same result Commented Dec 1, 2017 at 13:45
  • @chris85 each fetch will return one row and its not the point Commented Dec 1, 2017 at 13:50
  • Oh so you mean when you use $row outside of the loop you want the 1 row per return? $row[] = $rs->fetch();, still could just be done with 1 query though using the in(). Commented Dec 1, 2017 at 13:51
  • fetch() only returns 1 row. If you want all rows, use fetchAll() Commented Dec 1, 2017 at 13:55

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.