How to select a random row in MySQL and PHP? [duplicate] - php

This question already has answers here:
How to SELECT random rows from table with an exact number of row?
(2 answers)
Closed 8 years ago.
My table is like this:
id,url,name,imagelink
and I'd like to do something like:
SELECT * FROM id WHERE id="randomid"
I want to get all the data from a random row like id=17,url17,name17,imagelink17 and save it in variables afterwords. e.g $currentid,$currenturl, $currentname, $currentimagelink
I've tried something like that:
"SELECT * FROM table WHERE id= ORDER BY rand() LIMIT 20";
which obviously did not work. How can I do this correctly?

As you don't want a specific row, leave the WHERE id= out of the query and it should work.
SELECT * FROM table ORDER BY RAND() LIMIT 20
will return 20 random rows,
SELECT * FROM table ORDER BY RAND() LIMIT 1
will give you only one

Try something like this:
$query = "SELECT * FROM table_name ORDER BY RAND() LIMIT 1";
$result= mysqli_query($connection, $query);
and for the variables you can have
while($row = mysqli_fetch_array($result))
{
$currenid=$row['id'];
$currenturl=$row['url'];
$currentname=$row['name'];
$currentimagelink=$row['imagelink'];
}

You can have query like this:
SELECT * FROM table_name ORDER BY RAND() LIMIT 1

Related

MySQL Select from table depending on variable [duplicate]

This question already has answers here:
PHP Variable in Select Statement
(7 answers)
Closed 7 years ago.
I have the following problem:
I am trying to select a result from a MySQL database table, depending on the category value:
$sql = mysql_query("SELECT * FROM products WHERE category='garniture' ORDER BY date_added DESC LIMIT 2");
The problem is that I don't want to use a static value for category (like 'garniture'), but I want this to be determined by a variable value (let's say that variable is $category). How can I manage this?
Without getting into the fact that you should not be using the MySQL Library anymore, use MySQLi or PDO instead, you would insert a variable in that string as such:
$sql = mysql_query("SELECT * FROM products WHERE category='$category' ORDER BY date_added DESC LIMIT 2");
Or if you find it easier to read:
$sql = mysql_query("SELECT * FROM products WHERE category='" . $category . "' ORDER BY date_added DESC LIMIT 2");
$sql = mysql_query("SELECT * FROM products WHERE category='$category' ORDER BY date_added DESC LIMIT 2");
Just put the variable where you want it in the string.
The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.
See the PHP manual about string interpolation.

Mysql select list after a specific id

I'm trying to find a solution to select a list of rows coming after a certain Id from an ordered list.
For example, first I select 1000 rows. Then, on a subsequent request, i want to fetch another 1000 rows coming from after the last id of the first request. I know i can do it with limit, but suppose there has been 100 rows added between the first and second request, there will be 100 rows that will be from the first request.
Both queries will be ordered by the date of the entries.
Here's an example of the query I thought of:
$query = "SELECT * FROM table WHERE id AFTER $id ORDER BY date DESC";
$query = "SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT 1000";
Two ways to do this:
WHERE
"SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT $length"
LIMIT
"SELECT * FROM `table` LIMIT $start, $length"
$query = "SELECT * FROM table WHERE id > $id ORDER BY date LIMIT 1000";
You're asking about logic, not code so here it is.
The first request selects the first 1000.
$query = "SELECT * FROM the_table ORDER BY `date` DESC LIMIT 0,1000";
NB date is a reserved word so needs escaping if you've called a column "date" which you shouldn't.
$rs=$db->selectMany($query); // replace this with however you select the rows. $rs is results set
Do stuff with PHP and save the maximum id. They may not be in order.
$maxid=0;
foreach ($rs as $r){
// whatever you need to do with your results
$maxid=max($maxid, $r->id);
}
Your subsequent select uses the last id
$query = "SELECT * FROM the_table WHERE id > $maxid ORDER BY date DESC LIMIT 0,1000";
BUT you need to take note that you're ordering by date and using id to find a breakpoint which sounds like it would cause data to be missed.
Perhaps you mean to use WHERE`date`> $maxdate? If so you can figure that out from the code given.

How to select from 'table' WHERE column = *wildcard* [duplicate]

This question already has answers here:
MySQL Wildcard for "=" - is there one
(8 answers)
Closed 8 years ago.
When this code loads i want it to select everything and show it, and then be able to change the results with Ajax by altering the column row variable $data.
So how do i load column bbookschool with a wildcard and change it later?
$data = '_';
$Result = mysql_query("SELECT * FROM ads WHERE bbookschool = '$data' ORDER BY time desc limit 15")
i want to put a select list for values to be chosen which will be $data
Thanks
You might want to look at the LIKE operator:
SELECT foo FROM bar WHERE baz LIKE '%part-of-baz%'
Using LIKE and updating you $data should do the trick
You can use an or condition. When $data is the empty string, then the query will select everything:
SELECT *
FROM ads
WHERE bbookschool = '$data' or '$data' = ''
ORDER BY time desc
limit 15;

Invalid use of group function with MAX [duplicate]

This question already has answers here:
How do I select an entire row which has the largest ID in the table?
(6 answers)
Closed 9 years ago.
My code gives me the following error:
Invalid use of group function
$query = mysql_query("SELECT `text` FROM `text` WHERE `id`=max(id)");
if(!$query)
die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['text'];
}
Where is my mistake?
If you want the row with highest id you could use:
SELECT text FROM text ORDER BY id DESC LIMIT 1
WHERE clauses affect individual rows, whereas HAVING clauses affect aggregations (results of GROUP BY clauses). Row criteria must be limited to the WHERE clause, aggregate functions (like MAX) must be used in HAVING clauses.
You could do this:
SELECT *
FROM text
WHERE id = (SELECT MAX(id) FROM text);

PHP, MySQL: how to select random records without RAND (attempt to avoid RAND()) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to request a random row in SQL?
Because of a huge table I cannot use MySQL function RAND() and trying to avoid using RAND() this way:
$a = mysql_fetch_array(mysql_query("SELECT MIN(id), MAX(id) FROM table WHERE category_id='".$var."'"));
$id = rand($a[0],$a[1]);
$id2 = rand($a[0],$a[1]);
Which doesn't work, because: in $a I have the biggest and smallest ID with the respective category_id - that's ok.
The problem brings the rows with $id and $id2 - because there are used the minimal and maximal ID values, but PHP function rand() will take some random value between minimum and maximum - and there is a big probability, that the picked out record will not belongs into category_id.
So I would like to ask you about a way, how could I fix this example.
THank you
You could try this:
$row = mysql_fetch_assoc(
mysql_query(
"SELECT count(*) as count FROM table WHERE category_id='$var'"));
$randomrow = rand(0, $row['count'] -1);
$q = mysql_query("
SELECT * FROM table
WHERE category_id='$var'
LIMIT 1 OFFSET $randomrow");

Categories