Retrieve last row in array using end($array) - php

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?

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

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.

Try with array_pop function in php
$row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC);
$lastElement = array_pop($row2);
echo $lastElement

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;
}

Related

How to get the position of a row when a MYSQL table is ordered

I want to find the position of a row when I order the table in a descending order. I used the following to order the rows in a descending order.
SELECT * FROM feature Order BY Votes DESC
I need to find what position the row is in compared to others, such as 1st, 5th, 8th...
I was thinking of using a loop that loops through each value in the ordered from greatest to lowest and if the votes are greater than the previous value but more than the next value, then the position can be found. However, I found this to be impractical if there are many rows in the table. How can I find the relative standing of a row? A simple direction will be sufficient.
If I understand correctly, you could loop through the result as an assoc array, with an $i variable increased each iteration. That $i variable would tell you each row's position in order.
$query = "SELECT * FROM feature Order BY Votes DESC";
$result = mysqli_query($connect, $query);
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['idColumnName'];
if ($id == 'idNumber'){
echo("My ID is: ".$id." and I am voted number: ".$i);
}
$i++;
}

count columns from sql query

I'm trying to count the number of rows selected from a table by using the count() function. But it always returns either a '2' for every query with a row/rows selected or a '1' for every query with no row selected.
$sql_usb="select item_name from req_item where item_name='USB Dongle'";
$result_usb=mysql_query($sql_usb);
$row_usb=mysql_fetch_array($result_usb);
$sql_router="select item_name from req_item where item_name='Access Point/Router'";
$result_router=mysql_query($sql_router);
$row_router=mysql_fetch_array($result_router);
$sql_laptop="select item_name from req_item where item_name='Laptop'";
$result_laptop=mysql_query($sql_laptop);
$row_laptop=mysql_fetch_array($result_laptop);
$usb_inv=count($row_usb);
$router_inv=count($row_router);
$laptop_inv=count($row_laptop);
$total_inv=$usb_inv+$router_inv+$laptop_inv;
I've also tried adding isset() (i.e. $usb_inv=count(isset($row_usb));)
and mysql_num_rows() (i.e. $usb_inv=mysql_num_rows($row_usb));)
both give a result of 1.
You should use
SELECT COUNT(*) WHERE ....
Check the doc.
If you only need the total, then only 1 sql will be enough.
// please add error handing yourself.
$sql = "select count(*) from req_item where item_name
where item_name in('USB Dongle', 'Access Point/Router', 'Laptop')";
$result = mysql_query($sql);
$row = mysql_fetch_array($result)
$total = $row[0];
You have to use count in you mysql query like this
$SelectQuery = 'select Count(item_name) as [TotalUSB] from req_item where item_name='USB Dongle'
Then you can get the result by
$result = mysql_query($SelectQuery);
$row = mysql_fetch_array($result);
$USBCount = $row['TotalUSB'];
you should have used mysql_num_rows on result set.
like this.
$usb_inv=mysql_num_rows($result_usb);
$router_inv=mysql_num_rows($result_router);
$laptop_inv=mysql_num_rows($result_laptop);
this will give you proper output.
mysql_fetch_array is returning something like
$row[0] = ...;
$row[item_name] = ...;
If you are using count of an array, it will always return a two,
because it return an array with both index and associate key.
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
Despite the wrong usage of mysql_fetch_array,
you probably should just use a single query
$sql ="select item_name from req_item
where item_name in('USB Dongle', 'Access Point/Router', 'Laptop')";
after that,
$count = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
// do something else ...
// to get count for each item name
$count[$row["item_name"]]++;
}
You should use
$usb_inv = mysql_num_rows($result_usb);
instead of
$usb_inv=count($row_usb);

show 2 random rows instead of one

MY SQL QUERY:
$q = mysql_query("SELECT * FROM `ads` WHERE keywords LIKE '%$key%' ORDER BY RAND()");
RESULTS: KEYWORD123
This query searches and results in one random row but i want to show 2 random rows.
How to do that?
any solution?
how??
im grabbing it using this
$row = mysql_fetch_array($q); if ($row
<= 0){ echo 'Not found'; }else{ echo
$row['tab']; }
That query (as-is) will return more than one row (assuming more than one row is LIKE %$key%). If you're only seeing one record, it's possible you're not cycling through the result set, but rather pulling the top response off the stack in your PHP code.
To limit the response to 2 records, you would append LIMIT 2 onto the end of the query. Otherwise, you'll get every row that matches the LIKE operator.
//Build Our Query
$sql = sprintf("SELECT tab
FROM ads
WHERE keyword LIKE '%s'
ORDER BY RAND()
LIMIT 2", ('%'.$key.'%'));
// Load results of query up into a variable
$results = mysql_query($sql);
// Cycle through each returned record
while ( $row = mysql_fetch_array($result) ) {
// do something with $row
echo $row['tab'];
}
The while-loop will run once per returned row. Each time it runs, the $row array inside will represent the current record being accessed. The above example will echo the values stored in your tab field within your db-table.
Remove your order by and add a LIMIT 2
That happens after the execution of the SQL.
Right now you must be doing something like
$res = mysql_query($q);
$r = mysql_fetch_array($res);
echo $r['keywords'];
what you need to do
$q = mysql_query("SELECT * FROM ads WHERE keywords LIKE '%$key%' ORDER BY RAND() LIMIT 2");
$res = mysql_query($q);
while($r = mysql_fetch_array($res)){
echo "<br>" . $r['keywords'];
}
Hope that helps
This query will return all rows containing $key; if it returns only one now this is simply by accident.
You want to add a LIMIT clause to your query, cf http://dev.mysql.com/doc/refman/5.0/en/select.html
Btw both LIKE '%... and ORDER BY RAND() are performance killers

Select multiple values from the same row?

I have a script and I want to return 5 values from the database that have the same category but it is only returning one. Any ideas?
Here's the script:
$result = mysql_query("SELECT Category FROM GameData
WHERE Title=\"$title\" ");
//returns category to search in next select
$row= mysql_fetch_array($result);
$results = mysql_query("SELECT Title FROM GameData
WHERE Category=\"$row[0]\" LIMIT 5 ");
$rows= mysql_fetch_array($results);
print_r($rows); //returns $title from first select query
I'm new to databases and MySQL so any help would be much appreciated.
mysql_fetch_array just fetch one row in one call use loop to fetch multiple records
while($row= mysql_fetch_array($results))
{
print_r($row); //returns $title from first select query
}
You must loop over all the results: mysql_fetch_array returns one result row, so you have to call it multiple times:
while($row = mysql_fetch_array($results)) {
// here process ONE row
}
mysql_fetch_array will only fetch one row : if you want to fetch several rows, you'll have to call mysql_fetch_array several times -- in a loop, typically.
For a couple of examples, you can take a look at its manual page ; but, in your case, you'll probably want to use something like this :
$results = mysql_query("SELECT Title FROM GameData
WHERE Category='...' LIMIT 5 ");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
// work with $row['Title']
}
mysql_fetch_array only returns one row, you would have to loop through the rows
see example at: http://php.net/manual/en/function.mysql-fetch-array.php
You should use following query in order to make things right.
SELECT `Title` FROM GameData
LEFT JOIN
Category ON Category.Id = GameData.Category
WHERE Category.Title = "$title" LIMIT 5
I assumed that Category has column Id.
I advise you to learn about JOINS.
Additionally, you may want to rename Category to Category_Id, and drop letter-case so Category would become category_id.

Echo a selected id from MySQL table

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks
If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}
From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.
mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

Categories