Small Legend
Small Legend

Reputation: 688

Cannot output all rows of array in a database

Problem: Can only output one field from each array

 <?php
    error_reporting(0);
    session_start();
    include('connect.php');
    ob_start();

    $category = array(
        "dates" => array(),
        "paragraphs" => array(),
        "titles" => array()
    );

    if ($result = $mysqli->query("SELECT * FROM tips")){
        if($result->num_rows){
            while($row = $result->fetch_array(MYSQLI_ASSOC)){
            //printf ("%s %s %s\n",$row["date"], $row["title"], $row["paragraph"]); 
            $dates= array($row["date"]);
            $titles = array($row["title"]);
            $paragraphs = array($row["paragraph"]);
            }
            }
            $result->free();
        }

    ?>

I want the last in the array to be displayed first so I'm using this

<?php echo $titles[count($titles)-1]?>

I think the problem is with my loop, I think its reassigning the array each time it loops round

Upvotes: 0

Views: 48

Answers (2)

al&#39;ein
al&#39;ein

Reputation: 1729

Each iteration of while creates a new array in your vars, which first position stores current row data iteration.

It overwrites the last one each time, try not $data = array($row['data']) but $data[] = $row['data'].

This way you push the values of each iteration into a new index of the array.

Upvotes: 3

davidkonrad
davidkonrad

Reputation: 85528

you are not adding values to the $category array properly :

while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
   $category['dates'][] = $row["date"];
   $category['titles'][] = $row["title"];
   $category['paragraphs'][] = $row["paragraph"];
}

as it is now, with $dates= array($row["date"]) etc, you just assign the values to the same (never declared) $dates variable over and over.

Upvotes: 1

Related Questions