Using PHP to pull data from MySQL table column randomly - php

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"];

Related

Problems with MAX( ) MYSQL call

I'm having trouble using the MAX aggregate function in my PHO code. What I'm trying to do is to select the highest user_id form my database. However, I get an error that says " Warning: mysql_result() [function.mysql-result]: image_id not found in MySQL result index 3 " If anyone could tell me what I'm doing wrong with my code it would be greatly appreciated!
$highest = "Select MAX(image_id) FROM image_table ";
$result2 = mysql_query ($highest);
if (!$result2) die ("Database acces failed: " . mysql_error ());
$rows2 = mysql_num_rows($result2);
for ($j=0; $j<$rows2; $j++)
{
echo 'highest image id: ' . mysql_result($result2, $j,'image_id') . '<br/>';
}
Also, is there a way to set a variable directly equal to the highest id. Say for example i wanted the variable $maxID to be equal to the current maximum id, which is 93...
You have two choices:
Use an alias - SELECT MAX(image_id) AS image_id FROM image_table ...
Use an offset - mysql_result($result2, $j, 0)
Also, I would suggest switching over to PDO. Here's an example of that:
$db = new PDO( ... );
$res = $db->query('SELECT MAX(image_id) FROM image_table');
if (false === ($maxId = current($res->fetchAll(PDO::FETCH_COLUMN, 0)))) {
// $maxId is definitely a number
}

php random mysql data

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

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.

Checking If MySQL Rows Returned>10 and if so running some code, if not running a different piece of code

I have the code below which is supposed to check the database for entries with a certain username which is working but when I try to add some code to check if the rows returned is greater than 10 and then run some code to limit the number of rows to 10 and then if not run another piece of code which will display all the rows.
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$checkres = mysql_query("SELECT COUNT link, notes, titles, color FROM links WHERE username='" . $username . "';");
if ($checkres>10)
{
$resultsmall = mysql_query("SELECT link, notes, titles, color FROM links WHERE username='" . $username . "' LIMIT 10;");
while ($rowsmall = mysql_fetch_array($resultsmall)) { //loop
extract($rowsmall);
$htmlsmall .= "
//code goes here to format results
";
echo $htmlsmall; //display results...
}
}
else {
$result = mysql_query("SELECT link, notes, titles, color FROM links WHERE username='" . $username . "';");
while ($row = mysql_fetch_array($result)) { //loop
extract($row);
$html .= "
//code goes here to format results
";
echo $html; //display results...
}
}
mysql_close($con); //close db..
But it just displays two times the number of rows in the database instead of either limiting it or displaying them all. How would I fix this? The //code goes here for formatting isn't important it just formats the code so that it looks nice and displays it in a box...
Thanks!
EDIT:
I now have this code but it now doesn't display anything at all? Can someone help:
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT SQL_CALC_FOUND_ROWS link, notes, titles, color FROM links WHERE username='" . $username . "' LIMIT 10";
$result = mysql_query($sql) or die("MySQL error: " . mysql_error());
$subsql = "SELECT found_rows() AS foundrows;";
$subresult = mysql_query($subsql) or die("MySQL error: " . mysql_error());
$found_rows = $subresult['foundrows'];
if($found_rows > 10)
{
while($row = mysql_fetch_array($result))
{
extract ($row);
$html .= "
//getting values from columns and then formatting them goes here
";
echo "Only 10 is allowed.";
}
}
else
{
while($row = mysql_fetch_array($result))
{
extract($row);
$html .= "
//getting values from columns and then formatting them goes here
";
}
}
mysql_close($con); //close db..
Thanks!
EDIT 2 (12 April 14:03 2011 GMT):
I now have this code which has been kindly helped by Col. Shrapnel but it doesn't display anything for me and I don't know why, please could some help.
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT link, notes, titles, color FROM links WHERE username='$username' LIMIT 10";
$res = mysql_query($sql);
if (mysql_num_rows() == 10) {
while ($row = mysql_fetch_array($res)) {
extract($row);
$htmlsmall .= "
=
";
$htmlfree .= "Only 10 is allowed.";
echo $htmlsmall;
echo $htmlfree;
}
}
else {
while ($row = mysql_fetch_array($res)) {
extract($rowsmall);
$htmlsmall .= "
";
echo $htmlsmall;
}
}
Now if I view the page source I can see these 2 errors:
<b>Warning</b>: Wrong parameter count for mysql_num_rows() in <b>//url was here</b> on line <b>109</b><br />
<b>Warning</b>: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>//url to file goes here</b> on line <b>125</b><br />
Line 109 is this: if (mysql_num_rows() == 10) {
Line 125 is this: while ($row = mysql_fetch_array($res)) {
(Those lines are in the code above)
Please could someone help me with this?
Thanks!
mysql_query() returns either a result statement handle, or boolean FALSE if the query failed. Your outer query is invalid:
SELECT COUNT ...
does not work, so the query fails, returns false, which jumps to the lower "unlimited" query.
However, you're going about the process of limiting things in a roundabout fashion that forces the query to run at least twice.
What you want is
$sql = "SELECT SQL_CALC_FOUND_ROWS link, notes, etc.... LIMIT 10";
$result = mysql_query($sql) or die("MySQL error: " . mysql_error());
$subsql = "SELECT found_rows() AS foundrows;";
$subresult = mysql_query($subsql) or die("MySQL error: " . mysql_error());
$found_rows = $subresult['foundrows'];
if ($found_rows > 10) {
... there's more than 10 rows available, though we're fetching only 10 because of the LIMIT
} else {
... 10 rows or less
}
The SQL_CALC_FOUND_ROWS is a MySQL extension that forces MySQL to calculate how many rows would have been fetched, if the LIMIT clause had not been present. You can get the results of this calculation with the found_rows() query function.
This way, you only run the main query once, do the very very quick found_rows() query, and off you go.
Given that you don't seem to be formatting your output any differently between the "more than 10" and "10 or less" version, except for the "only 10 allowed" line, how about this:
$sql = "...";
$result = mysql_query($sql) or die(mysql_error());
$rowcount = 0;
while ($row = mysql_fetch_assoc($result)) {
$rowcount++;
... output a row ...
if ($rowcount > 10) {
echo "Only 10 allowed";
break;
}
}
There's no need for duplicated code, excess logic, etc... when something simple will do.
I try to add some code to check if the rows returned is greater than 10 and then run some code to limit the number of rows to 10
It makes no sense.
Just run your query with LIMIT 10 and you will get your data.
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT * FROM links WHERE username='$username' LIMIT 10";
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
while ($row = mysql_fetch_array($res)) {
extract($rowsmall);
$htmlsmall .= ""; //code goes here to format results
}
echo $htmlsmall;
That's all.
If you still want to echo "Only 10 is allowed." (dunno why though) you can add these 3 lines below
if (mysql_num_rows($res) == 10) {
echo "Only 10 is allowed.";
}
However I see not much point in it.
Also note that your program design is probably wrong, as you're apparently copying this file for the every user in your system
To get number of rows returned in result you must use mysql_num_rows.
if (mysql_num_rows($checkres)>10)

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