Ross
Ross

Reputation: 49

Ordering and then setting variables

I have the following code which orders my data in mysql perfectly:

<?php

$con = mysql_connect('localhost','root','password');
mysql_select_db("users");

$pop = mysql_query("
SELECT * FROM images ORDER BY pop DESC LIMIT 9

");

while($row = mysql_fetch_array($pop))
    {
    echo $row['imagefile'];
    echo "<br />";
    }




mysql_close($con);



?>

However i would like for each "result" to then automatically be assigned as a variable. So for example "uploads/logo.png" comes out as the first "result" of the above code. I would then want this to be assigned $image_1 - so in code it would read $image_1 = "uploads/logo.png". I then want all the other 8 outputs to be assigned to variables so that $image_2 corresponds to the second output and so on. This is only a prototype. I wish for it to eventually output 100 results. Is this at all possible? Thanks a lot for your time.

Upvotes: 0

Views: 51

Answers (1)

Adam Lockhart
Adam Lockhart

Reputation: 1195

Use an array.

$images = array();
while($row = mysql_fetch_array($pop))
    $images[] = $row['imagefile'];

Or keep the associative array:

$imageData = array();
while($row = mysql_fetch_array($pop))
    $imageData[] = $row;

// $imageData[0]['imageFile'] will be "uploads/logo.png"

Edit for comment below:

First method from above:

<?php
foreach ($images as $image) {

    echo <<<EOT
<div class="box"><img src= "$image" width="200" height="150"></a></div>
EOT;
}
?>

Second method could be more involved, depending on your data:

<?php
foreach ($imageData as $image) {
    $imagePath = $image['imageFile'];
    $imageWidth = $image['width'];
    $imageHeight = $image['height'];
    echo <<<HTML
<div class="box"><img src= "$imagePath" width=$imageWidth height=$imageHeight></a></div>
HTML;
}
?>

Upvotes: 2

Related Questions