help needed modifying code to select random database table rows
My own PHP and SQL knowledge is fairly limited, but growing slowly.
I need help modifying some code in a piece of software. I didn't write this code myself.
The above function selects random rows from a certain table. What I need to do is restrict the rows which can be selected by putting in an additional condition based around the "category_id" field of the table, but I don't honestly think I can work out how to do this myself with my limited knowledge.
function random_rows($table_name, $table_fields, $condition, $nb_rows, $debug = false)
(array) $random_numbers = null;
(array) $primary_fields_array = null;
(array) $result = null;
(int) $counter = 0;
$table_rows = $this->count_rows($table_name, $condition);
//$table_rows = ($table_rows > 100) ? 100 :$table_rows;
$total_rows = ($table_rows > $nb_rows) ? $nb_rows : $table_rows;
while ($counter < $total_rows)
$number = rand(0, ($table_rows-1));
if (!@in_array($number, $random_numbers))
$random_numbers = $number;
foreach ($random_numbers as $value)
$result = $this->get_sql_row("SELECT " . $table_fields . " FROM
" . $this->db_prefix . $table_name . " " . $condition . " LIMIT " . $value . ", 1", $debug);
There are two other tables I know will need to be referenced in the above function. One is "categories" and another is "users"...
I know that in the categories table there will be two relevant fields: "minimum_age" and "category_id", and in the users table there will be two relevant fields: "user_id" and "show_adult".
If the currently logged in user's database entry has a value of 0 in the "show_adult" field then when the above function selects random rows it needs to exclude any rows where the "category_id" is matched to the "category_id" in the categories table and the corresponding "minimum_age" in the categories table has a value of 18. Whereas if the currently logged in user's database entry has a value of 1 in the "show_adult" field then the above function should run as it currently does.
Although I pretty much understand what the code needs to do, how to write it is beyond my current knowledge (I could probably write it in BASIC though haha!). Any help greatly appreciated.
EDIT: I realise the above function probably uses other custom functions within it that cannot be seen above, but I figure those shouldn't be relevant for making the changes I need.
Last edited by tr0ub1es0me; 07-02-2012 at 04:49 PM.
make two functions
It is a can of worms. Firstly the current function seems to be guarenteed of _X random selects, and it cannot be modified in its current form.
The best way would be to reduce the result with individual checks.
Knowledge is that which can be shown to be the case, and Intelligence is the method one uses to deploy the demonstration of what is the case, everything else is Information.
For a stronger Text reading try:
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)