need another pair of eyes pls on this array..

wilsoc31

New member
for the life of me, im overlooking something. this line is inside of a loop but at the end, it only has the last record. why???

Thanks in advance

$response = array();

while ($row = mysqli_fetch_array($get_tour,MYSQLI_ASSOC))
{
$response = array(["name"=>"$tour_name","dates"=>"$print_start","datee"=>"$print_end","location"=>"$city,$state"]);
}
echo json_encode($response);

[{"name":"TURKEY RUN EVENT-OPEN-$595","dates":"11-16-2024","datee":"11-17-2024","location":"Redding,CA"}]
 
In your loop:


PHP:
$response = array(); // Initialize an empty array

while ($row = mysqli_fetch_array($get_tour, MYSQLI_ASSOC)) {
// Assign values to $response array
$response = array(["name"=>"$tour_name","dates"=>"$print_start","datee"=>"$print_end","location"=>"$city,$state"]);
}

  • Initialization: You correctly initialize $response as an empty array before the loop starts.
  • Loop Logic: Inside the loop, you are assigning a new array to $response in each iteration. This assignment overwrites any previous data in $response. So, after the loop finishes, $response will contain only the data from the last iteration.

Solution:
PHP:
$response = array(); // Initialize an empty array

while ($row = mysqli_fetch_array($get_tour, MYSQLI_ASSOC)) {
    // Assuming $row contains relevant data
    $tour_name = $row['tour_name'];
    $print_start = $row['print_start'];
    $print_end = $row['print_end'];
    $city = $row['city'];
    $state = $row['state'];

    // Build each record as an array and push it to $response
    $response[] = array(
        "name" => $tour_name,
        "dates" => $print_start,
        "datee" => $print_end,
        "location" => "$city, $state"
    );
}

// Now $response contains all records fetched from the database
echo json_encode($response);
  • Appending to $response: Instead of assigning a new array ($response = array(...)) inside the loop, we use $response[] = array(...) to append each record as a new element in the $response array.
  • Fetching Data: Inside the loop, $row represents each fetched record from the database ($get_tour). You should access specific fields ($tour_name, $print_start, $print_end, $city, $state) from $row based on your database schema.


Best Regard
Danish Hafeez | QA Assistant
ICTInnovations
 
Back
Top