3

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. :)

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Here's the solution:

while($stmt->fetch())
{
    foreach($result as $key=>$value)
    {
        $tmp[$key] = $value;
    }
    $skins[$i] = $tmp;
    $i++;
}

Posted on behalf of the question asker

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.