Jacob Windsor
Jacob Windsor

Reputation: 6980

Pushing mysql data into an array

Okay so I need to push the array that is fetched from a few different tables into a new array. I thought this would do it but it doesn't. A warning saying array_push() expects parameter 1 to be an array. There is probably something really simple that I have done wrong but Im new to all this PHP stuff so have no idea. I thought the parameter 1 is an array as an array is fetched from database.

Here's the code:

$newsfeed = array("apple");

$news = mysql_query("
SELECT * FROM news
UNION ALL
SELECT * FROM feature ORDER BY timestamp DESC LIMIT 1
")or die(mysql_error());

while($row = mysql_fetch_array($news))
{

    $artist = mysql_query("
    SELECT * FROM members WHERE artist='Y'
    ORDER BY timestamp DESC LIMIT 2
    ")or die(mysql_error());

    while($row1 = mysql_fetch_array($artist))
    {
        array_push($newsfeed, $row['title'], $row1['artistname']);
    }
}
echo($newsfeed);

Upvotes: 0

Views: 8487

Answers (3)

Jonathan
Jonathan

Reputation: 585

Could you do something like.

$artists=array();
$artists[ $row['title'] ] = $row1['artistname'];

Or am I misunderstanding the question?

Upvotes: 0

sachleen
sachleen

Reputation: 31131

Look at the documentation for array_push. The first parameter must be the name of the array you're pushing into.

array_push($myArray, $row['title'], $row1['artistname']);

$myArray will now have $row['title'] and $row1['artistname'] in it.

You're also missing braces on the while loop. You can only omit braces when there is only one line following it. It's still good practice to have braces anyway.

If you want to see the value of an array, you should use print_r instead of echo.

If you want to print out the elements of the array, you'll need to loop through them. Then you can use echo, when you're only printing one element of the array. You can't use it for an entire array or it'll just print array. See the foreach documentation for examples on how to do this:

$arr = array("one", "two", "three");
foreach ($arr as $value) {
    echo $value;
}

Upvotes: 2

Habeeb
Habeeb

Reputation: 166

$row['title'] is not an array.. it's an element of the array $row.

If you want to store all 'title' and 'artistname' to an array, you can do it

$artists = array();
array_push($artists, $row['title'], $row1['artistname']);
print_r($artists);

If you want to group 'title' and 'artistname'

$artists = array();
$artist_data = array('title' => $row['title'], 'artistname' => $row['artistname'])
array_push($artists, $artist_data);
print_r($artists);

Upvotes: 2

Related Questions