Reputation:
After doing some research I hear that to retrieve the last row on an array I can use end($arrayname)
However when putting this into my page it does not retrieve the last, but the first in the array.
$query2 = "SELECT * FROM Items";
$resultSet2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC))
{
$lastElement = end($row2);
echo $lastElement;
}
Looping through the array like this will loop through and display every row in the array one after the other: Agate & Labradorite Necklace.jpgAgate Necklace.jpgAventurine, Citrine and Carnelian Necklace.jpg
However I was under the impression it should simply repeat the last item (Carnelian necklace.jpg) every time
$row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC);
$lastElement = end($row2);
echo $lastElement
This will print the first item in the array. Any ideas what is causing this to happen?
Upvotes: 0
Views: 104
Reputation: 94
you can try this :
$query2 = "SELECT * FROM Items DESC limit 1";
$resultSet2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC))
{
echo $lastElement = $row2;
}
Upvotes: 0
Reputation: 437664
You are applying end
to $row2
, which already represents a row of data. This makes $lastElement
be the last column of each row (the while
iterates over rows).
It would not make sense to fetch N items just so that you can repeat the last one of them N times (in addition: your SQL query does not specify a sort order, so which item is going to be last is also unknown to you). If you wanted to do something like that you would fetch one item using LIMIT 1
and the number N using an appropriate query and finally simply use a for
loop.
Upvotes: 0
Reputation: 44864
Why to do so much trouble just select the last row in the query as
SELECT * FROM Items order by primary_key desc limit 1
primary_key
is the column name of your table which is primary key
Upvotes: 1
Reputation: 18600
Try with array_pop function in php
$row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC);
$lastElement = array_pop($row2);
echo $lastElement
Upvotes: 0