Hi. Trying to setup a MySQL Database I've created a db with one table (for now, adding more in the future). Every table has 5 columns, named "nom_base","nom","edat","centre" and "imatge". I'm not using indexes to make faster queries.
What I want to do is: Given an array with the name of every table, select one table. Then, inside that table, I want to select a random row, fetch it as an array and assign it's data to some variables. I tried this code:
I get this:
regarding this line:
inside the select_random_row($table) function.
I'm guessing that the method I use to retrieve a random row doesn't work, but I have no clue.
What I want to do is: Given an array with the name of every table, select one table. Then, inside that table, I want to select a random row, fetch it as an array and assign it's data to some variables. I tried this code:
PHP:
<?php //DATABASE_SCRIPT.PHP
$db_user = "username"; // Username
$db_pass = "pass"; // Password
$db_database = "DB"; // Database Name
$db_host = "localhost"; // Server Hostname
$database = mysql_connect ($db_host, $db_user, $db_pass); // Connects to the database.
$db_connect = mysql_select_db($database);// Selects the database.
function select_random_row($table){
$result = mysql_query("SELECT * FROM ".$table." ORDER BY RAND() LIMIT 0,1");
// ALTERNATE METHOD: (can't get it to work)
//$string = "SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM ".$table;
//$offset_result = mysql_query($string);
//$offset_row = mysql_fetch_object( $offset_result );
//$offset = $offset_row->offset;
//$result = mysql_query( "SELECT * FROM ".$table." LIMIT ".$offset.", 1");
return $result;
}
?>
<?php //EMBEDDED IN INDEX.PHP
$CENTRES = array(
"COSTA" //Only one table at the moment
);
$row1 = "";
$row2 = "";
while ($row1 == $row2){
$row1 = select_random_row($CENTRES[array_rand($CENTRES, 1)]);
$row2 = select_random_row($CENTRES[array_rand($CENTRES, 1)]);
$row1DATA = mysql_fetch_array($row1);
$row2DATA = mysql_fetch_array($row2);
$Nom_base1 = $row1DATA['nom_base'];
$Nom1 = $row1DATA['nom'];
$Edat1 = $row1DATA['edat'];
$Institut1 = $row1DATA['centre'];
$Nom_base2 = $row2DATA['nom_base'];
$Nom2 = $row2DATA['nom'];
$Edat2 = $row2DATA['edat'];
$Institut2 = $row2DATA['centre'];
}
?>
I get this:
Fatal error: Maximum execution time of 30 seconds exceeded
regarding this line:
PHP:
$result = mysql_query("SELECT * FROM ".$table." ORDER BY RAND() LIMIT 0,1");
inside the select_random_row($table) function.
I'm guessing that the method I use to retrieve a random row doesn't work, but I have no clue.