【问题标题】:How to retrieve data from all options if user selects `All`如果用户选择“全部”,如何从所有选项中检索数据
【发布时间】:2013-01-18 11:56:48
【问题描述】:

下面有一个 mysqli/php 代码,它将根据从 question 下拉菜单中选择的选项显示结果:

$selectedquestionqry = "
SELECT
QuestionNo
FROM
Question
WHERE
(QuestionId = ?)
";

global $mysqli;
$selectedquestionstmt=$mysqli->prepare($selectedquestionqry);
// You only need to call bind_param once
$selectedquestionstmt->bind_param("i",$_POST["question"]);
// get result and assign variables (prefix with db)
$selectedquestionstmt->execute(); 
$selectedquestionstmt->bind_result($selQuestionNo);
$selectedquestionstmt->store_result();
$selquestionnum = $selectedquestionstmt->num_rows();   


 while ($selectedquestionstmt->fetch()) {

if($_POST["question"] === '0') {
    echo "<p>All Questions - Total:(" . $selquestionnum . ")</p>" . PHP_EOL;
}else if($_POST["question"] !== '0') {
echo "<p><strong>Questions: </strong>" . $selQuestionNo . "</p>" . PHP_EOL;
}
}

下拉菜单:

 <select name="student" id="studentsDrop">
    <option value="0">All</option>
    <option value="23">Jay Hart</option>
    <option value="32">Bubba Wright</option>
    </select>

我的问题是,我怎样才能得到它,以便如果用户选择了“0”,那么它将能够从数据库中选择question 下拉菜单中显示的所有问题?

我问这个的原因是因为在我的回声else if($_POST["question"] !== '0') { echo "<p><strong>Questions: </strong>" . $selQuestionNo . "</p>" . PHP_EOL; } 中,当我选择All 选项时没有回声,这让我认为它没有因此显示回声。如果我从下拉菜单中选择一个问题,它能够输出它的回声。

【问题讨论】:

  • 使用这些条件处理您的查询,当 question === 0 时删除查询中的 where 子句

标签: php mysql mysqli


【解决方案1】:

你只需要修改你的查询:

if($_POST["question"] === '0') {
    $selectedquestionqry = "SELECT QuestionNo FROM Question";
} else {
    $selectedquestionqry = "SELECT QuestionNo FROM Question WHERE (QuestionId = ?)";
}

【讨论】:

    【解决方案2】:

    您需要更改查询以删除基于发布值为'0'WHERE 条件。此后您不必更改任何代码,因为您已经在循环,但您应该在循环之外显示 Total。

    【讨论】:

      猜你喜欢
      • 2013-01-14
      • 2017-01-20
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多