You have a line which i don't understand:
$random_row = mysql_fetch_row(mysql_query("select * from YOUR_TABLE order by rand() limit 1"));
is this the ads table? it doesn't relate to anything else. Looks like you're looping through domains.
using order by rand() is fine as long as you're not talking about 100s of thousands of records.
I suggest you have a table of ads, and then a 1-many table of keywords for those ads.
then have another table of domains, and a 1-many table of keywords for those domains.
finally, joining these tables gives you similar keywords and this focuses the ads you can show. It woudl also reduce server load. Hope my answer's helpful.
Sam