Hi I have a MySQL table with 14 columns and between 1 and 10 entries in rows beneath each column. I wish to randomly call one entry from each column to make a random combination of entries. Given that a column might only have one entry beneath it then that entry would then be called every time... if it had only 2 entries then it would call 1 of the 2, if it had 10 then it would call 1 of the 10 etc. all random!
I used this suggestion by Matthew McGovern and it works great but it only calls a few entries across the columns and not one from each of the 14.
Can I modify the code to make it call one from each?
His 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);
// 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)][3] . " "
. $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " "
. $rows[rand(0, $max)][4] . " " . $rows[rand(0, $max)][5];
?>
array_rand()is better.$rows = array();? Does the same thing either way?mysql_*functions will be deprecated in PHP 5.5. It is not recommended for writing new code as it will be removed in the future. Instead, either the MySQLi or PDO and be a better PHP Developer.