0

Why am I only getting last value in this array outside while loop. Shouldn't it hold all records? Why array is not built with all the values from query?

This is my code.

$cost_array = array(); 
if ($stmt = $conn_mysqli -> prepare("SELECT costs_items.cno, costs_items.name,costs_items.description, costs_items.type,costs_items.measure, costs_items.amount, costs_items.vc_fc,costs_items_custom.cno, costs_items_custom.name, costs_items_custom.description, costs_items_custom.type, costs_items_custom.measure, costs_items_custom.amount, costs_items_custom.vc_fc FROM costs_items LEFT JOIN costs_items_custom ON costs_items.costs_id = costs_items_custom.costs_id WHERE costs_items.costs_id = ?")) {
         $stmt -> bind_param("i", $costs_select);   
         $stmt -> execute();
         $stmt -> bind_result($cno, $cost_name, $cost_description, $cost_type, $cost_measure, $cost_amount, $cost_vcfc, $ccustom_cno, $ccustom_name, $ccustom_description, $ccustom_type, $ccustom_measure, $ccustom_amount, $ccustom_vc_fc);
         while($stmt -> fetch()){

            //Here we put all costs in array
            $cost_array['cno'] = $cno;
            $cost_array['cost_name'] = $cost_name;
            $cost_array['cost_description'] = $cost_description;
            $cost_array['cost_type'] = $cost_type;
            $cost_array['cost_measure'] = $cost_measure;
            $cost_array['cost_amount'] = $cost_amount;
            $cost_array['cost_vcfc'] = $cost_vcfc;

        }
        $stmt -> close();                                      }

    var_dump($cost_array);

2 Answers 2

1

Change your code to this:use [] to create new index.

 $cost_array = array(); 
while($stmt -> fetch()){
    $cost_array['cno'][] = $cno;
    $cost_array['cost_name'][] = $cost_name;
    $cost_array['cost_description'][] = $cost_description;
    $cost_array['cost_type'][] = $cost_type;
    $cost_array['cost_measure'][] = $cost_measure;
    $cost_array['cost_amount'][] = $cost_amount;
    $cost_array['cost_vcfc'][] = $cost_vcfc;

}
$stmt -> close();          

var_dump($cost_array);//all your values
Sign up to request clarification or add additional context in comments.

1 Comment

That's it. Thank you!
1

Try this way

 $cost_array[] = array(
      'cno' => $cno,
      'cost_name' => $cost_name,
      'cost_description' => $cost_description
    );

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.