NonStopCoding Posted September 27, 2014 Share Posted September 27, 2014 Hello i been having some issues with a mod i been working on <?php $a = mysql_query("SELECT `id` FROM `tablename` ORDER BY RAND() DESC LIMIT 1"); $b = mysql_fetch_array($a); $c = mysql_query("SELECT `target` FROM `tabletwo` WHERE `target` <> '".$b['id']."'"); $d = mysql_fetch_array($c); ?> What i am trying to do is select 1 person at random and make sure this person is not in the second table then insert them into the second table if this is not true but for some reason the not equal the id that is selected. on the occasion that it did select the same id i did something like this <?php if($b['id'] == $c['target']) { $a = mysql_query("SELECT `id` FROM `tablename` ORDER BY RAND() DESC LIMIT 1"); $b = mysql_fetch_array($a); } else { insert the info } ?> Quote Link to comment Share on other sites More sharing options...
sniko Posted September 27, 2014 Share Posted September 27, 2014 Multiple ways you can go about this. Perhaps embrace a unique key on the database table? CREATE TABLE `table_2` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(20) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `user_id` (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1; insert into table_2 (username, user_id) values('foo', 1); #Inserted. insert into table_2 (username, user_id) values('foo', 1); #Duplicate entry '1' for key 'user_id'. Quote Link to comment Share on other sites More sharing options...
NonStopCoding Posted September 28, 2014 Author Share Posted September 28, 2014 (edited) oops was meant to click thanks. Thanks for the reply sniko i have never used unique before will give it a try EDIT: Thanks worked like a charm and did not even need to use as much code as i used thanks :) Edited September 28, 2014 by NonStopCoding Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.