0

I want to have all results from my database in one array

my function:

function GetWinkelProduct($g_Winkel) {
    global $g_Conn;

    $l_Stmt = $g_Conn->prepare("SELECT pd_id FROM `producten_:Winkel`");
    $l_Stmt->bindValue(':Winkel', $g_Winkel, PDO::PARAM_INT);
    $l_Stmt->execute();


    $l_qurries = new dbquery();
    $l_LastProduct = $l_qurries->GetLastProduct($g_Winkel);

    while($l_Row = $l_Stmt->fetch(PDO::FETCH_ASSOC)){
        $out = array();

        foreach($l_Row as $product){
            $out[] = $product['pd_id'];
        }
    }
        return $out;        
}

other page: <?php print_r($l_qurries->GetWinkelProduct($g_Winkel)); ?>

only I get the first result in the array and when I do $product['pd_id'] I get only the last result.

4
  • no need of foreach loop inside while loop Commented May 27, 2015 at 11:58
  • You've initialized the array inside the while loop. Commented May 27, 2015 at 11:58
  • 1
    @javabrett I deleted the foreach loop though it was needed but only with a while loop it works fine. Commented May 27, 2015 at 12:02
  • you'r welcome @Erwin !! enjoy!! Commented May 27, 2015 at 12:02

2 Answers 2

2

Try this...

Change fetch to fetchAll in while loop and renove foreach inside while loop

function GetWinkelProduct($g_Winkel) {
    global $g_Conn;

    $l_Stmt = $g_Conn->prepare("SELECT pd_id FROM `producten_:Winkel`");
    $l_Stmt->bindValue(':Winkel', $g_Winkel, PDO::PARAM_INT);
    $l_Stmt->execute();


    $l_qurries = new dbquery();
    $l_LastProduct = $l_qurries->GetLastProduct($g_Winkel);

    while($l_Row = $l_Stmt->fetchAll(PDO::FETCH_ASSOC)){
        $out = array();


            $out[] = $l_Row ['pd_id'];

    }
        return $out;        
}

ref:http://php.net/manual/en/pdostatement.fetchall.php

Sign up to request clarification or add additional context in comments.

Comments

0

You must initialize the array outside the while loop and you don't need the foreach.

that way you are creating a new array every time the while iterates, that way you end up replacing the array.

    $out = array();    
    while($l_Row = $l_Stmt->fetchAll(PDO::FETCH_ASSOC)){
          $out[] = $l_Row['pd_id'];
    }
    return $out;        

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.