Mysqli选择多个查询

时间:2014-09-11 23:47:59

标签: php mysql mysqli

我正在尝试使用user_id选择一个查询来获取特定于用户的类别,然后从那里使用第一个查询的结果从第二个查询中的第二个表中选择数据。我希望在下拉菜单中显示第二个查询的数据。有没有简单的方法来做到这一点?我是新手使用mysqli所以请耐心等待。

我有以下功能,但它没有在下拉菜单中显示任何内容,但它显示的是下拉菜单。

function get_classes($mysqli) {
     if(isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
    $user_id = $_SESSION['user_id'];
    if ($stmt = $mysqli->prepare("SELECT category_id 
                            FROM questions WHERE user_id = ?")) {
        $stmt->bind_param('i', $user_id);
        $stmt->execute();
        $stmt->store_result();

        if($stmt->num_rows>0) {
            $stmt->bind_result($category_id);
            $stmt->fetch();
            if($result = $mysqli->prepare("SELECT category_id, category_name
                            FROM category WHERE category_id = ?")) {
                $result->bind_param('s', $category_id);
                $result->execute();
                $result->store_result();
            }
        }
        echo "<select id='classes' name='classes'>";
        while ($row = $result->fetch_assoc()) {
            unset($user_id, $category_name);
            $category_id = $row['category_id'];
            $category_name = $row['category_name'];
            echo '<option value="'.$category_id.'">'.$category_name.'</option>';
        }
        echo "</select>";
    }

}
}

我正在使用以下代码从另一个页面调用该函数:

<?php
            get_classes($mysqli);

            ?>

2 个答案:

答案 0 :(得分:1)

您可以通过一个SQL查询来完成所有操作:

SELECT c.category_id, c.category_name
  FROM questions q
  INNER JOIN category c ON c.category_id = q.category_id
  WHERE q.user_id = ?

答案 1 :(得分:0)

或者,你可以加入它们,然后是正常的提取。例如:

function get_classes($mysqli) {
    if(!isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
        return false;
    }

    $user_id = $_SESSION['user_id'];

    $sql = '
        SELECT
        category.category_id,
        category.category_name

        FROM category
        JOIN questions
        ON questions.category_id = category.category_id

        WHERE questions.user_id = ?
    ';
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param('i', $user_id);
    $stmt->execute();
    $result = $stmt->bind_result($category_id, $category_name);

    // printing
    echo '<select name="classes" name="classes">';
    while($row = $stmt->fetch()) {
        echo '<option value="'.$category_id.'">'.$category_name.'</option>';
    }
    echo '</select>';
}