show 2 random rows instead of one - php

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

Related

Flagging last overall row in MySQL query using LIMIT

I am retrieving results from a database in batches of 5, each time taking the last 'id' and returning it via jquery so only rows with smaller 'id' are returned. I have a load more button which should disappear after all rows are loaded, even if that means 5, 7 or 11 rows.
I have this query:
$query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 5");
$query->execute([$_POST["id"]]);
while($row = $query -> fetch()) {
echo "<div id="$row["id"].">".$row["name"]."</div>";
});
The question is, is there an easy and performant way to add a column to flag each row if it's last or not in a single query? Considering I am using LIMIT of 5, obviously the query should also check the potential existence of 5+1 row.
Set the limit to 6 and check the number of returned rows.
for the while loop, use a counter:
$query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 6");
$query->execute([$_POST["id"]]);
$n=5;
while($row = $query -> fetch() && $n-->0)
{
echo "<div id="$row["id"].">".$row["name"]."</div>";
}

Retrieve last row in array using end($array)

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

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)

saving a column in an array

I'm trying to fetch random no. of entries from a database by using
SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10
it returns a column of database.
If I want to save all the entries in a array, then which php function do I have to use to save the column.
Something along the lines of this?
$result = mysql_query("SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10");
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row[0];
}
Updated to not use the $i variable as pointed out in the first post and the comment.
Look at some examples for how to run a query and get a result set.
http://www.php.net/mysqli
Once you have the result in a variable, do this:
$myarray = array();
while($row = mysqli_fetch_row($result))
$myarray[] = $row[0];
With PDO:
$qryStmt = $dbc->query('SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10');
$a = $qryStmt->fetchAll( PDO::FETCH_COLUMN );
BTW: If you just want to get one row by random, this is much faster esp. for large tables:
select * from table limit 12345,1;
where 12345 is just a random number calculated from the count() of rows.
see here, which is more for rails, but have a look at the comments too.
But be careful: in limit 12345,2 - the second row is not random but just the next row after the random row. And be careful: When I remember right (eg. SQLServer) rand() could be optimized by databases other than mysql resulting in the same random number for all rows which makes the result not random. This is important, when your code should be database agnostic.
a last one: do not mix up "random" with "hard to predict", which is not the same. So the order by example "select top 10 ... order by rand()" on SQLServer results in two different result sets when run twice, BUT: if you look at the 10 records, they lie close to each other in the db, which means, they are not random.

Categories