# Miscellaneous > Database Programming >  help needed modifying code to select random database table rows

## tr0ub1es0me

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.



```
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;
				$counter++;
			}
		}

		if (is_array($random_numbers))
		{
			foreach ($random_numbers as $value)
			{
				$result[] = $this->get_sql_row("SELECT " . $table_fields . " FROM
					" . $this->db_prefix . $table_name . " " . $condition . " LIMIT " . $value . ", 1", $debug);
			}
		}

		return $result;
	}
```

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.

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 completely relevant for making the changes I need.

----------

