使用mysqli_fetch_assoc()构建一个id数组

时间:2017-03-03 02:17:52

标签: php mysqli

我正在尝试使用mysqli来获取“用户”已回答的一系列“问题”。我有一个questions_users表来实现这一目标,我使用以下代码查找用户,然后获得他们已经回答的所有问题,并构建一个他们的id数组,以便我可以排除这些问题被选为新的问题要回答。

$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";
}

问题在于我正在构建$ qusAnswered数组。从数据库中的内容来看,它应该只包含值3,因为这是他们已经回答的问题的id。出于某种原因,$ qusAnswered实际上看起来像

array('1','2');

我不确定我做错了什么,如果有人可以为我指出显而易见的事情,我会很感激。

var $ newQuestionSql中的SQL看起来像:

SELECT * FROM questions WHERE id NOT IN (1,2) LIMIT 1

它应该是:

SELECT * FROM questions WHERE id NOT IN (3) LIMIT 1

2 个答案:

答案 0 :(得分:0)

好吧,我的加入也不如我想的那么好,但是这里是如何在一个查询中执行此操作,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
}

答案 1 :(得分:0)

我想建议你只是一个简单的查询。

可能会解决你的问题

SELECT * from questions where id IN (SELECT GROUP_CONCAT(question_id) FROM `questions_users` WHERE `user_id`=1)