I'm trying to use mysqli to get an array of 'questions' which 'users' have answered. I have a questions_users table to achieve this and I'm using the following code to find a user and then get all the questions they've answered, and build an array of their id's so I can exclude these questions from being picked as a new question to answer.
$qusAnswered = array();
$DoWeHaveUsersql = "SELECT * FROM users WHERE `checkid`=".$checkid;
$DoWeHaveUserresult = $conn->query($DoWeHaveUsersql);
if ($DoWeHaveUserresult->num_rows > 0) {//we've got a user
$row = mysqli_fetch_assoc($DoWeHaveUserresult);
$userId = $row['id'];
$checkQuestionSql = "SELECT * FROM questions_users WHERE `user_id`=".$userId;//get all the questions_users records
$checkQuresult = mysqli_query($conn, $checkQuestionSql);
if (mysqli_num_rows($checkQuresult) > 0) {
// make an array of all the id's of questions answered
while($Qu = mysqli_fetch_assoc($checkQuresult)) {
$qusAnswered[] = $Qu['question_id'];
}
}
$newQuestionSql = "SELECT * FROM questions WHERE id NOT IN (".implode(',', $qusAnswered).") LIMIT 1";
}
The problem is when I'm building the $qusAnswered array. From what's in the database it should contain only the value 3, because thats the id of the question they've answered. For some reason $qusAnswered actually looks like
array('1','2');
I'm not sure what I'm doing wrong and if anyone can point out the obvious for me I'd appreciate it.
the SQL which is in the var $newQuestionSql looks like:
SELECT * FROM questions WHERE id NOT IN (1,2) LIMIT 1
it should be:
SELECT * FROM questions WHERE id NOT IN (3) LIMIT 1
Well my join-fu is not as good as I thought, but here's how to do this in one query, and without opening yourself to SQL injection attacks:
$query = "SELECT * FROM questions WHERE question_id NOT IN (
SELECT question_id FROM questions_users WHERE user_id=?
);"
$userid = $_GET["user_id"];
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $userid);
$stmt->execute();
$result = $stmt->get_result();
$rows = $result->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
//do stuff with $row
}
I would like to suggest you just simple one query.
Might be it will solve your problem
SELECT * from questions where id IN (SELECT GROUP_CONCAT(question_id) FROM `questions_users` WHERE `user_id`=1)