首页 > 解决方案 > 如何从选择表单中获取值到 SQL 查询中

问题描述

我有一个用户登录的项目,然后可以回答多个测验。这些测验有一个选择表格,他们可以在其中选择他们想要多少问题。我的问题是当他们选择他们想要多少个问题时,我不知道如何将其转换为 PHP 变量,然后在 SQL QUERY 中使用它。我的 SQL QUERY 看起来像这样:

SELECT questions FROM quiz_questions ORDER BY RAND() LIMIT=?

请在回答问题时解释一下谢谢:)

我试图将选择表单的变量设置为 $number。但是当我尝试用 echo 测试它时,我什么也没得到。我使用 iframe 因为我需要页面不要重新加载,因为我以后有一些 javascript 函数。

  <form target="frame" action="UvodniNivo.php" method="post">
    <div class="center">
      <label>izberite št. vprašanj:&nbsp;</label>
        <select name="number" id="value">
          <option value="5">5</option>
          <option value="10">10</option>
          <option value="15">15</option>
        </select>
    </div>
    <button onclick="hide()" name="start-btn" type="submit">Začni</button>
  </form>
  <iframe name="frame"></iframe>

                       <!--Start of the quiz-->


  <div id="SHOW">
  <?php

    if(isset($_POST['start-btn'])){
    $select="SELECT * FROM quiz_question ORDER BY RAND() LIMIT=?";
    $result= mysqli_query($conn, $select);
    $count= mysqli_num_rows($result);
    if($count < 1)
    {
      echo "ERROR";
    }
    else
    {
      while($row= mysqli_fetch_array($result))
      {
        echo $row[2]."<br />";
      }
    }
    ?>
  </div>

编辑: $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

DB_HOST、DB_USER、DB_PASS、DB_NAME 都具有正确的值,因为登录/注册工作。

标签: phpsql

解决方案


首先,您正在使用准备好的语句,因此您必须初始化 stmt ,准备语句,将语句与参数绑定并执行..

<?php
if(isset($_POST['start-btn'])){

$select="SELECT * FROM quiz_question ORDER BY RAND() LIMIT=?";
$numOfQuestions = $_POST['number']; //make sure you sanitize this
$q = mysqli_stmt_init($conn);
mysqli_stmt_prepare($q, $select);
mysqli_stmt_bind_param($q, 'i', $numOfQuestions );
mysqli_stmt_execute($q); 

$result = mysqli_stmt_get_result($q);
if (mysqli_num_rows($result) != 0) {
     // do stuff here
}

?>

推荐阅读