Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with array when getting data from a database

I'm trying to get some data from my database, and then pass it into an array for later use. I am using MySQLi for my driver.

Here's my code:

// Build a query to get skins from the database
$stmt = $mysqli->prepare('SELECT id, name, description, author, timestamp, url, preview_filename FROM `skins` LIMIT 0, 5');
$stmt->execute();
$stmt->bind_result($result['id'], $result['name'], $result['desc'], $result['auth'], $result['time'], $result['url'], $result['preview']);

// The skins array holds all the skins on the current page, to be passed to index.html
$skins = array();
$i = 0;
while($stmt->fetch())
{
    $skins[$i] = $result;
    $i++;
}

print_r($skins);

The problem is, when this executes, the $skins array contains the last result row from the query. This is the print_r of $skins:

Array
(
    [0] => Array
        (
            [id] => 3
            [name] => sdfbjh
            [desc] => isdbf
            [auth] => dfdf
            [time] => 1299970810
            [url] => http://imgur.com/XyYxs.png
            [preview] => 011e5.png
        )

    [1] => Array
        (
            [id] => 3
            [name] => sdfbjh
            [desc] => isdbf
            [auth] => dfdf
            [time] => 1299970810
            [url] => http://imgur.com/XyYxs.png
            [preview] => 011e5.png
        )

    [2] => Array
        (
            [id] => 3
            [name] => sdfbjh
            [desc] => isdbf
            [auth] => dfdf
            [time] => 1299970810
            [url] => http://imgur.com/XyYxs.png
            [preview] => 011e5.png
        )

)

As you can see, the last result from the query is populating all of the array entries for some reason.

Can anyone explain this behaviour and tell me what I'm doing wrong? Thanks. :)

like image 771
Josh Avatar asked Feb 01 '26 07:02

Josh


1 Answers

Quoting the (now) first note on the mysqli::fetch manual page, emphasis mine :

the problem is that the $row returned is reference and not data.
So, when you write $array[] = $row, the $array will be filled up with the last element of the dataset.

like image 107
Pascal MARTIN Avatar answered Feb 03 '26 21:02

Pascal MARTIN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!