So, I'm learning PHP and MySQL, but I have run into a little problem here.
I do lack some information, so this will be very helpful to me =)
I do a query against my database, and get a result. This result is all my image files to be listed.
$fileSQL = $mysqli->query("
SELECT *
FROM content
WHERE projID=$projectID
");
So, if I want to list all my files as thumbnails on my page I do this:
<?php while($row = $fileSQL->fetch_assoc()){ ?>
<img src="assets/<?=$row['contentFull']?>" id="thumbImg"
onclick="document.getElementById('mainImage').src=this.src" width="110px" height="62px"/>
<?php } ?>
Now, this works fine, of course. It loops through all the rows while adding a for each of them.
However, I do have a main image too, where I need to show the first thumb in full (for this example I use contentFull
both for thumbs and fullsize).
Now, how do I get the first row's contentFull
, without making the while loop start from row nr.2?
And in general; what is the best way to do in these situations? Store the result to an array first, so I can access it easily, or what is the "normal" way of doing it? =)
What I need:
Thanks in advance, and please let me know if you need more information =)
One simple options would be to do this:
<?php
$first = null;
while($row = $fileSQL->fetch_assoc()) {
if(!isset($first)) $first = $row;
?>
<img src="assets/<?=$row['contentFull']?>" id="thumbImg"
onclick="document.getElementById('mainImage').src=this.src" width="110px" height="62px"/>
<?php } ?>
Now you have the first row stored in a variable to use, without having to store all the results in an array. If for some reason you want all rows stored in an array you could simply do this:
<?php
$rows = array();
while($row = $fileSQL->fetch_assoc()) {
$rows[] = $row;
//rest of code
}
?>
Then you could access first row by referencing $rows[0]
Another option would be to not use php to populate the full image. Instead use a javascript call to populate the first image.
I think you could take your first picture outside the while
loop:
$row = $fileSQL->fetch_assoc(); // the first picture
if($row){
// show first image if it exists
}
while ( $row = $fileSQL->fetch_assoc()) // etc.
Probably code for larger image is different than for others, so it could be reasonable. If not, consider defining a function, or use a counter (or flag like in Pitchinnate's answer).