I was wondering whether anyone could shed some light on a mysql/php problem I've been having.
I have the following two tables.
Table: Postedposts
|id |textid |modelid |timeposted |
|1 |2 |1 |0000-00-00 00:00:00|
Table: Text
|textid |text |
|2 |hello |
I need to randomly select one text value from table Text where the textid has never been inserted into table Postedposts for a particular modelid. If this returns no results I need to randomly select one text value from table Text where the textid has not been inserted into table Postedposts for a particular modelid within the last 7 days.
So far I have the following code for the initial problem but I can't work out how to limit it to a particular modelid.
$sql="
select Text.textid,Text.text
from Text left join Postedposts on Text.textid = Postedposts.textid
where ((Postedposts.textid IS NULL)) ORDER BY RAND() LIMIT 1
";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($result);
$text = $row['text'];
Any help whatsoever would be greatly appreciated.
Thank you :)
In case anyone was wondering I eventually solved this myself with the following:
$modelid = 1;
$minustime = date('Y-m-d H:i:s', strtotime('-7 days'));
$sql = "SELECT a.*
FROM Text a
LEFT JOIN Postedposts b
ON a.textid = b.textid AND
b.modelid = ".$modelid."
AND b.timeposted > '".$minustime."'
WHERE (b.textid IS NULL) ORDER BY RAND() LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$text = $row['text'];
echo "<br><br>".$text;
}
}
else
{
echo "no rows";
}
Please let me know if/how this can be improved? Thanks