php random mysql data - php

I have a MySQL database with 6 columns in a table. There will eventually be about 100 rows, for now I have 3.
Column titles: FirstName, SecondName, Sentence1, Sentence2, Sentence3, Sentence4
All tables are set to VARCHAR
I want to use php on a web page to call random data from each row, eg mix and match row1 FirstName with row3 SecondName and row2 Sentence1 etc.
I read it is quicker to randomise using php but I really can't grasp how to do this despite searching.
I can connect to my MySQL database and get results returned using this code:
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error ());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['FirstName'] . "<br />";
}
// Close the database connection
mysql_close();
?>
but this just returns one column of data. I need the random code to be returned in the webpage using something like:
echo $firstname . $lastname . $sentence1 . $sentence2 . $sentence3 . $sentence4;
Note, this will be repeated for another 3 or 4 rows afterwards too
echo $firstname_2 . $lastname_2 . $sentence1_2 . $sentence2_2 . $sentence3_2 . $sentence4_2;
I'm not too hot on arrays but if someone can get me started it would be great, thanks.

All those telling you to use rand in the SQL query have not read the question. To those people: the asker wants a random combination of data from the rows, not a random row.
Something like this. It will take all the results from the database and echo a totally random combination. I couldn't avoid using arrays as they are super useful.
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error ());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Array to hold all data
$rows = array();
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// add row to array.
$rows[] = $row;
}
// Close the database connection
mysql_close();
// Max rand number
$max = count($rows) - 1;
// print out random combination of data.
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4] . " " . $rows[rand(0, $max)][5];
?>

Store all the values which you want to show in random in a variable, use rand() http://php.net/manual/en/function.rand.php and shuffle() http://php.net/manual/en/function.shuffle.php to make the random data and display them

there are several methods to get random data from db in php
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;
another method: -
$range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM `table` ");
$range_row = mysql_fetch_object( $range_result );
$random = mt_rand( $range_row->min_id , $range_row->max_id );
$result = mysql_query( " SELECT * FROM `table` WHERE `id` >= $random LIMIT 0,1 ");
one more method:-
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `table` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `table` LIMIT $offset, 1 " );

SELECT * FROM `Users` ORDER BY RAND() LIMIT 0,1;

Use ORDER BY RAND() for random records selection.

Split it into two tables,
one for the user
Users:
id | firstname | lastname
Sentences:
id | userId | sentence
Join both at the "id / userId" and do a ORDER BY RAND() probably followed by a LIMIT 20

Trying to implement this but taking an entry from every column (14 at present) instead of a small random number. Would love to have Matthew McGovern's opinion since his code suited me except that it only called a few entries...
Here: Random Sentence Using PHP & MySQL

Related

Using PHP to pull data from MySQL table column randomly

I am using the following (assume I already plan to change these to mysqli at a later date and am aware of the insecurity of the queries used), to pull text strings from rows in one column in a MySQL table and the output in a browser would, ideally, be a randomly selected string from this column:
mysql_connect($host,$username,$password);
mysql_select_db($database) or die(mysql_error ());
$query="SELECT * FROM `tablename` ORDER BY RAND() LIMIT 0,1;";
$result=mysql_query($query);
$rows = array();
while($row = mysql_fetch_array($rs)) {
$rows[] = $row;
}
mysql_close();
$max = count($rows) - 1;
Using the following echo line to achieve the last bit in the browser:
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4]$
?>
I receive the error "PHP Notice: Undefined offset: 0 in script.php on line 19" in reference to this echo line (which, admittedly, was pieced together from other threads and tutorials, so I do not follow completely), however, I've since resolved all other errors logged and observed, so if possible, how can I amend this so the output is just a single row (the text within it) from the column?
Faster and better than using RAND()
$conn = mysqli_connect($host,$username,$password, $database);
if($conn->connect_errno > 0) {
die('Unable to connect to database [' . $conn->connect_error . ']');
}
$total_rows = 20; //Generate Random number. You could get $total_rows with a first query counting all rows.
$selected_row = mt_rand(0, $total_rows);
//$selected_row -= 1; //just in case you randomized 1 - $total_rows and still need first row.
//Use the result in your limit.
$query="SELECT * FROM `tablename` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["columnname"];
}
Edit it from mysql to mysqli (on the fly). You would not want to use RAND() if your table is very large. Believe me!
In your SELECT-statement, you are telling the database to order the strings randomly. So just get the first one and echo it:
$row = mysql_fetch_array($rs)
echo $row['name_of_field_you_want_to_echo'];
You never define the variable $rs. Other than that...
If you are selecting the first items from a SQL query, you don't need to specify both the limit and top.
$result = mysql_query("SELECT * FROM `tablename` ORDER BY RAND() LIMIT 1");
Since that will ever return one row, you can use mysql_fetch_row
$row = mysql_fetch_row($result);
and then you can get the field from that row with
echo $row["column_name"];

variables should get values randomly from mysql table and at the same time belong to same row

I have made a form that asks the user to put in first name and last name and stores it in MySQL database
Now in another file i want to use the database in the table randomly
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT `column` FROM `table` ORDER BY RAND() LIMIT 1");
//what should i write here if i want get the randomly selected row data in the following variable
//$firstname = " ";
//$lastname = " ";
mysql_close($con);
?>
basically i want $firstname $lastname to get values randomly from MySQL table and at the same time belong to same row
You're nearly there - the query is already set up correctly to retrieve 1 random row from the table. You just need to specify which columns to retrieve, and call mysql_fetch_*() on the result to populate your variables:
// ...
// Do the query
$query = "
SELECT `firstname_col`, `lastname_col`
FROM `table`
ORDER BY RAND()
LIMIT 1
";
$result = mysql_query($query) or trigger_error(mysql_error()." ".$query);
// Fetch the selected row into an associative array
$row = mysql_fetch_assoc($result);
// Assign the variables
$firstname = $row['firstname_col'];
$lastname = $row['lastname_col'];
// ...

How to reverse an array in PHP that is fetched from MYSQL

I am trying to pull out a row of data from MySQL and put it in an array and then reverse it before displaying the results and then if confirmed by the user it will post the reversed results back into mysql
I am using this code :
for($i=0;$i<6;$i++) {
// Make a MySQL Connection
$query = "SELECT * FROM databasedemo WHERE id='$i'";
$result = mysql_query($query)or die(mysql_error());
$row = mysql_fetch_array($result);
array_reverse($row,true);
echo $i."--"."A".$row['A']. " - ". "B".$row['B']. " - ". "C".$row['C']. " - ". "D".$row['D']. " - ". "E".$row['E'];
echo "<br>";
}
I am getting this error
Warning: array_reverse() [function.array-reverse]: The argument should be an array in /home/nlp4mark/public_html/Databasedemo/main.php on line 37
Any help would be really appreciated. Thanks.
You should only be executing this query once and then iterating through the results and displaying them:
$query = "SELECT * FROM databasedemo ORDER BY id DESC";
$query = "SELECT * FROM databasedemo WHERE id='$i'";
That query will return a one record at the time. You are sending it 6 times with the for loop, that's why you get all the records, but you send 6 times a slighty different query.
try sending one query that return all the 6 records and then reverse it. It would be something like this
$sql = "SELECT * FROM databasedemo WHERE 1=1";
for($i=0;i<6;$i++){
$sql .= " AND id=$i";
}
do like this
select * from (SELECT * from messages INNER JOIN logindata ON messages.author = logindata.id ORDER BY messages.mid DESC LIMIT 0,10) as t ORDER BY t.mid asc

SQL Multiple Update Statements

I need to update 40 rows in a database, starting at the point where the userID is a match. I do not want to have to determine the row number because eventually this database will be huge.
What I would like to do is simply say:
"Update these the next 40 rows with my array where userID = myUserID"
Here is what I have:
<?php
// connect to the database and select the correct database
$con2 = mysql_connect("localhost","Database","Password");
if (!$con2)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ifaves_code", $con2);
$i = 0;
while ($i < 40) {
//cycle through the array
$cycleThrough2 = $updatedUserNames[$i];
//$query = "UPDATE tblUserLinks SET `URLName` = '$cycleThrough2' WHERE userID = '" . $mainUID . "' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
++$i;
}
mysql_close();
?>
The variable $mainUID is being set correctly, the problem I'm having is it appears there are no updates taking place in the database.
How can I alter my existing code to receive my desired behaviour?
I don't suppose it's because you have your query building statement commented out...
//$query = "UPDATE tblUserLinks SET `URLName` = '$cycleThrough2' WHERE userID = '" . $mainUID . "' LIMIT 1";
If this is just the result of debugging and it wasn't working before that, you must call mysql_error() right after mysql_query() to see why it is failing.
$result = mysql_query($query);
if (!$result) echo mysql_error();
Also, you are using LIMIT 1 at the end, but the userID never changes in the WHERE clause. Therefore, you are updating the same row over and over 40 times on each loop. What you need is a way in your WHERE clause to identify rows which have already been modified, and exclude them. Otherwise, the same row (first match) will always be caught by the LIMIT 1 and updated.

php mySQL, retrieve one row by number, store values as assoc.array

Pretty new to all this, so if I am going about my puzzle in a crazy way please tell me!
I have a table in a mySQL database with the columns title, hyperlink, imagelink
I want the php to select a row at random, then be able to save the title, hyperlink and imagelink as php variables. (so I can then output them into html)
so I could have for e.g
psuedoey code to get the idea
chosenNumber = randomNumber();
$chosenTitle = title[chosenNumber]
$chosenHyperlink = hyperlink[chosenNumber]
$chosenImagelink = imagelink[chosenNumber]
echo "<a href = $chosenTitle><img src= $chosenImagelink/> $chosenTitle </a>";
I think I need to use an assoc array like this here but I am very confused, because I looked through the various php mySQL fetch_assoc fetch_row etc and can't find which one to do what i need :(
What I have so far is
// database table name information
$number = "number";
$title = "title";
$hyperlink = "hyperlink";
$imagelink = "imagelink";
// sql to select all rows of adverts
$sql = "SELECT $number, $title, $hyperlink, $imagelink FROM $table";
//execute the sql
$data = mysql_query($sql, $link);
//count the number of rows in the table
$bannerCount = mysql_num_rows($data);
//generate a random number between 0 and the number of rows
$randomNumber = mt_rand(0, $bannerCount); //do I need to do bannerCount-1 or similar here?
$chosenNumber = $randomNumber;
//select data from a random row
First time post, be kind please, and thanks for any replies or explanations!
Using ORDER BY RAND() LIMIT 1 is a decent way to get a single row out of a smaller table. The downside to using this method is that RAND() must be calculated for every row in the table, and then a sort must be performed on this non-indexed value to calculate the row you want. As your table grows, ORDER BY RAND() becomes horribly inefficient. The better way to handle this is to first get a count of the number of rows in the table, calculate a random row number to read, and use the LIMIT [offest,] count option on your SQL query:
$sql = "SELECT COUNT(*) as rows FROM $table"
$res = mysql_query($sql);
if (!$row = mysql_fetch_assoc($res)) {
die('Error Checking Rows: '.mysql_error());
}
$rows = $row['rows'];
// now that we know how many rows we have, lets choose a random one:
$rownum = mt_rand(0, $rows-1);
$sql = "SELECT number, title, hyperlink, imagelink FROM $table LIMIT $rownum,1";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
// $row['number'] $row['title'] etc should be your "chosen" row
This first query asks the SQL Server how many rows are available, then LIMITs the result set of the actual query to only return 1 row, starting at the random number row we picked.
I think if you use the "limit" clause, it would be quite efficient:
SELECT number, title, hyperlink, imagelink FROM $table order by rand() limit 1
Why do you set up variables for the table name and field names?
If you want to get records randomly, you can simply modify your sql query and each time you will get random ordering of records, just add order by rand() to your query and limit clause if you want to get just one random record:
$sql = "SELECT $number, $title, $hyperlink, $imagelink FROM $table
order by rand() limit 1";
Once you have done that, you need to use functions like mysql_fetch_array or mysql_fetch_object to get the rows actually:
$data = mysql_query($sql, $link);
while ($row = mysql_fetch_array($data))
{
echo $row['title'] . '<br />';
echo $row['hyperlink'] . '<br />';
echo $row['imagelink'] . '<br />';
}
With:
$row = mysql_fetch_array($data)
You have $row array available at your disposal to echo values at any place of your page like:
echo $row['title'];
echo $row['hyperlink'];
echo $row['imagelink'];

Categories