Adam
Adam

Reputation: 507

When I try to access to array items I only get the 1. one

Here's my Query

$rows = $mydb->get_results("SELECT title, description  
FROM site_info
WHERE site_id='$id';");

I get something like:

Title1 Desc1
Title2 Desc2
etc.

I want to put that data in array so I do:

    $data = array();
foreach ($rows as $obj) {
        $data['title'] = $obj->title;
        $data['description'] = $obj->description;
}

When I do:

print_r($data);

I only get title and description of first item... Please help :/ I checked and my query returns all what i want to be in array not only the first row.

Upvotes: 2

Views: 41

Answers (2)

mickmackusa
mickmackusa

Reputation: 47894

If the eventual goal is simply to display these values, then you shouldn't bother with re-storing the data as a new multi-dimensional array.

$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id='$id';");

If $id is user-supplied data or from an otherwise untrusted source, you should implement some form of sanitizing/checking as a matter of security. At a minimum, if the $id is expected to be an integer, cast it as an integer (an integer doesn't need to be quote-wrapped).

$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id = " . (int)$id);

When you want to display the object-type data, just loop through $rows and using -> syntax to echo the values.

echo "<ul>";
    foreach ($rows as $obj) {
        echo '<li>' , $obj->title , ' & ' , $obj->description , '</li>';
    }
}
echo "</ul>";

If you have a compelling reason to keep a redundant / restructured copy of the resultset, then you can more simply command php to generate indexes for you.

foreach ($rows as $obj) {
    $data[] = ['title' => $obj->title, 'id' => $obj->id];
}

The [] is just like calling array_push(). PHP will automatically assign numeric keys while pushing the associative array as a new subarray of $data.

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

You are over-writing array indexes each time in iteration.You need to create new indexes each time when you are assigning the values to array.

So either do:-

$data = array();
foreach ($rows as $key=>$obj) { // either use coming rows index
   $data[$key]['title'] = $obj->title;
   $data[$key]['description'] = $obj->description;
}

Or

$data = array();
$i=0; //create your own counter for indexing
foreach ($rows as $key=>$obj) {
   $data[$i]['title'] = $obj->title;
   $data[$i]['description'] = $obj->description;
   $i++;// increase the counter each time after assignment to create new index
}

For display again use foreach()

foreach ($data as $dat) {
   echo $dat['title'];
   echo $dat['description'];
}

Upvotes: 3

Related Questions