Home > Software engineering >  Trying to retrieve data from SQL Server DB using PHP and only get 1 for rowcount when there are 1000
Trying to retrieve data from SQL Server DB using PHP and only get 1 for rowcount when there are 1000

Time:02-07

So, I'm trying to retrieve data from a data base on my own Actual Rows coming back in the DB

UPDATE BECAUSE OF DALE

        if ($stmtproducts->fetch(PDO::FETCH_ASSOC)) {
            printf("Inside IF for rows - " . $row . "<br>");
            while ($row = $stmtproducts->fetch(PDO::FETCH_ASSOC)) {
                $products_arr = array(
                    "status" => true,
                    "id" => $row['Product_Key'],
                    "productcd" => $row['Product_Code'],
                    "title" => $row['Title']
                );
                print_r(json_encode($products_arr) . "<br>");

            }
            $obj = (object) [
                "status" => 200,
                "statusText" => "Success",
                "data" => $products_arr
            ];
            echo json_encode($obj, JSON_PRETTY_PRINT);
        } else {
            $products_arr = array(
                "status" => false,
                "message" => "Invalid Username and Password!",
            );
        }

Re-run this to see the different results:

enter image description here

CodePudding user response:

You're creating $products_arr multiple times in a loop but you are only ever ending up with one element in the array.

Instead of $products_array = array(...) (which will replace the contents of $products_array every time with one single element), you need to use $products_array[] = array(...), which will push an element to the end of the $products_array:

This should give you an array of elements:

   if ($stmtproducts->fetch(PDO::FETCH_ASSOC)) {
        printf("Inside IF for rows - " . $row . "<br>");
        while ($row = $stmtproducts->fetch(PDO::FETCH_ASSOC)) {
            $products_arr[] = array(
                "status" => true,
                "id" => $row['Product_Key'],
                "productcd" => $row['Product_Code'],
                "title" => $row['Title']
            );
            print_r(json_encode($products_arr) . "<br>");

        }
        $obj = (object) [
            "status" => 200,
            "statusText" => "Success",
            "data" => $products_arr
        ];
        echo json_encode($obj, JSON_PRETTY_PRINT);
    } else {
        $products_arr = array(
            "status" => false,
            "message" => "Invalid Username and Password!",
        );
    }
  •  Tags:  
  • Related