Issue with rand() function in PHP - php

I'm having a little trouble with my rand() function. I have the following query:
$listTrainers = mysqli_query($conn, "SELECT emp_id FROM employees;");
while($fetchTrainers = mysqli_fetch_row($listTrainers))
{
echo 'ID: ' . $fetchTrainers['0']. '<br>';
}
This query returns me the id of all employees in the database, is there a way I can randomly select one of these id's and store it in a variable?
I am trying to use the following function:
echo(rand(begin, end));
where begin is the first element from the query and end is the last element

add this to your query:
ORDER BY RAND() LIMIT 1

You can do so within your query easily
SELECT emp_id FROM employees ORDER BY RAND() LIMIT 1

The easiest way is to do this directly in the database, to avoid getting all IDs if you only need one:
SELECT
emp_id
FROM
employees
ORDER BY
RAND()
LIMIT
1
If you do need all IDs, but additionally want to pick a random one, use this to avoid querying the database twice:
$listTrainers = mysqli_query($conn, "SELECT emp_id FROM employees;");
while($fetchTrainers = mysqli_fetch_row($listTrainers))
{
$id = $fetchTrainers[0];
echo 'ID: ' . $id . '<br>';
$ids[] = $id;
}
$randomId = $ids[array_rand($ids)];

Related

How do I display data retrieved from mysql db in a specific order using php

I am trying to display questions, along with the users answer in a specific order, NOT ASC or DESC, but as defined by the "question_order" column.
I have the following tables in a mysql db:
questions (qid, question_text)
answers (aid, uid, answer)
usermeta (userid, question_order)
"questions" table contains the questions
"answers" table contains every users answers to all questions
"usermeta" table contains the sort order for the questions in "question_order".
"question_order" is unique per user and is in the db as a pipe delimited list. (i.e.: 85|41|58|67|21|8|91|62,etc.)
PHP Version 5.3.27
If this entire procedure can be better accomplished using a completely different method, then please let me know.
My PHP ability is limited. With that said, below is what I have at the moment after several hours of playing ...
$sql = "
SELECT
*
FROM
".USERMETA_TABLE."
WHERE
userid = {$userid}
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row = $result->fetch_assoc();
$order_array = explode('|', $row['question_order']);
$sql = "
SELECT
*
FROM
".QUESTIONS_TABLE."
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row = $result->fetch_assoc();
// my attempt at sorting the questions. the $order_array
// does not have a unique id so I am kind of lost as to
// how to make this work
usort($myArray, function($order_array, $row) {
return $order_array - $row['qid'];
});
$sql = "
SELECT
*
FROM
".QUESTIONS_TABLE."
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
while ( $row = $result->fetch_assoc() )
{
$sql = "
SELECT
*
FROM
".ANSWERS_TABLE."
WHERE
uid = {$userid}
AND
qid = ".$row['qid']."
LIMIT
1
";
$result2 = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row2 = $result2->fetch_assoc();
echo ' <p>'.$row['question_text'].'</p>'."\n";
echo ' <p>'.$row2['answer'].'</p>'."\n";
}
Filter out the data when retrieving from db.
Use:- SELECT * FROM [TABLE_NAME] ORDER BY qid DESC
Then in PHP you can use session variables and modify the values accordingly.
If you want to order using ID you can use
SELECT * FROM [TABLE_NAME] ORDER BY qid DESC
this will order in descending order If you want in ascending order use ASC
I went ahead and altered the DB by adding a table to store the question numbers, user sort order, and student user id:
student_id, sort_order, question_id
1 1 8
1 2 2
1 3 97
and then was able to select it all with the following statement:
SELECT q.*
FROM
questions q
JOIN questions_sorting_order qso
ON q.id = qso.question_id
ORDER BY qso.sort_order
WHERE qso.student_id = $student_id
...works great.
Thanks to FuzzyTree for his help on this at: How do I sort data from a mysql db according to a unique and predetermined order, NOT asc or desc

php database table select limited

im new on php programming and i've searched the function that i need but didn't found it.
here what exactly i want to do :
i want to select 2 columns from a table
set the order by descending by 1 column that is numeric
and then show in php the first 100 rows that were selected
Here is my code right now php shows all the columns i want it to show the first 100
$result = mysqli_query($con,"SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC");
while($row = mysqli_fetch_array($result))
{
echo $row['pvpkills'] . "&nbsp " . $row['char_name'];
echo "<br>";
}
SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC LIMIT 0,100

Is it ok to query inside a while loop?

I have two tables in one database. I am querying the first table limit by 10 then loop the results. And inside the while loop, I am doing again another query using a data from the first query as a parameter. Here is an example of the script:
<?php
$con = mysql_connect(host,username,password);
mysql_select_db(game_server);
//My first query
$q1 = mysql_query('SELECT * FROM game_characters ORDER BY score DESC LIMIT 10');
while($character = mysql_fetch_object($q1)){
//My second query
$q2 = mysql_query('SELECT * FROM game_board WHERE id="'.$character->id.'"');
$player = mysql_fetch_object($q2);
}
?>
So if I have a result of 100 rows, then the second query will execute 100 times. And I know it is not good. How can I make it better. Is there a way to do everything in one query? What if there is another query inside the while loop where a data from the second query as a parameter is used?
P.S.: I am doing a rankings system for an online game.
You can do it in one query if you use JOINs.
SELECT * FROM game_board AS b
LEFT JOIN game_characters AS c ON b.id = c.id
ORDER BY c.score DESC
LIMIT 10
You can also use nested query
SELECT * FROM game_board AS b WHERE
id IN (SELECT id FROM game_characters AS c ORDER BY score DESC LIMIT 10)
You can also put all game_character.id into an array, and use
$sql = "SELECT * FROM game_board AS b WHERE b.id IN (" . implode(', ', $game_character_ids) . ")";
Why not using JOIN?
This way there will be no queries within the while loop:
$con = mysql_connect(host,username,password);
mysql_select_db(game_server);
//My first query
$q1 = mysql_query('
SELECT *
FROM game_characters gc
LEFT JOIN game_board gb ON gc.id = gb.id
ORDER BY score DESC
LIMIT 10
');
while($character = mysql_fetch_object($q1)){
// do Your stuff here, no other query...
}
A better approach here would be to collect all the IDs in a concatenated string str in form 'id1', 'id2', 'id3', ... and use:
select * from game_board where id in (str)
What about if you do something like the following:
<?php
$con = mysql_connect(host,username,password);
mysql_select_db(game_server);
//My first query
$q1 = mysql_query('SELECT * FROM game_characters ORDER BY score DESC LIMIT 10');
while($character = mysql_fetch_object($q1)){
//My second query
$characters .= " ' $character->id ' ,"
}
$q2 = mysql_query("SELECT * FROM game_board WHERE id in (substr($characters,0,strlen($characters - 2))");
$player = mysql_fetch_object($q2);
?>

mysql + php: Selecting multiple random results

I've been looking for this for a while but with no success.
I am trying to implement a recomendation bar, for example like in youtube, when you are seeing a video it shows the list or recommended videos on the right.
At this moment I am using this method:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `$tablename` ");
$offset_row = mysql_fetch_object($offset_result );
$offset = $offset_row->offset;
$result_rand = mysql_query( " SELECT * FROM `$tablename` LIMIT $offset, 9 " );
This works fine, but sometimes doesn't show any result, and the problem is also that its not completely random, because it shows for example the first ID as 200, so the next result will be id 201 and then 202 and so.
I would like to know if there is a way to show this 9 randon results, for example 1º result id 500, 2º result id 10, 3º result id 788, etc etc?
Thank you
Not entirely sure this answers what you are looking for, but try:
$result_rand = mysql_query("SELECT * FROM " . $tablename . " ORDER BY RAND() LIMIT 9");
You can use php rand() function to create 5 numbers and save them in an array:
http://php.net/manual/en/function.rand.php
<?php
$rand_array = array();
for($i=1;$i<5;$i++) {
$rand_array[$i] = rand(0,500);
}
?>
and after that create a query with every int with a foreach loop and work with your data.
<?php
foreach ($rand_array as $integer) {
$q = "SELECT * from $tablename WHERE id='$integer';";
}
?>
Does this helps?
First you should use mysqli_ functions instead of mysql_ because the latter is deprecated. Second use order by rand() to get random rows:
$rand_result = mysqli_query( "SELECT * FROM $tablename ORDER BY RAND() LIMIT 9;" );
UNTESTED:
SELECT id, #rownum:=#rownum+1 AS rownum, name
FROM users u,
(SELECT #rownum:=0) r
THis will give a unique number to each row in sequence. Now if you create a temp table with 9 random numbers between 1 and count(*) of your table and JOIN those two together...
Not sure about performance but seems like it might be faster than Rand and order by since I only need 9 random numbers

Mysql ORDER BY numbers DESC

I have a simple mysql select query in my PHP code:
$result = mysql_query("SELECT text FROM example ORDER BY rank DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] . "<br>";
}
and this MySql table:
text | rank
--------+--------
google | 245
--------+--------
yahoo | 32
--------+--------
bing | 12
When I get the results from the query, something like this gets displayed:
yahoo
google
bing
I want Google to be in front. I guess Yahoo is in first because it starts with "3".
How could I make the query order the results by the size of the numbers in rank?
Thanks...
I'm guessing the rank field is some kind of string type. Make it a numeric type int and it will order properly
The correct solution, of course, is to use the correct data type. As a workaround you could cast the data to number on the fly:
SELECT text FROM example ORDER BY rank + 0 DESC
or:
SELECT text FROM example ORDER BY cast(rank as unsigned) DESC
What's the data type of rank in your SQL schema? Set it to a numeric type.
Try this:
$result = mysql_query("SELECT * FROM example ORDER BY rank DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] . " ". $row['rank'] ."<br>";
}
And see if the ranks are being sorted correctly.
$result = mysql_query("SELECT * FROM `example` ORDER BY `rank` DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] ."<br>";
}

Categories