简体   繁体   中英

How to get a value from select form into SQL query

I have a project where a user logs in and can then answer multiple quizzes. These quizzes have a select form where they can select how many questions do they want. My problem is when they select how many questions they want i don't know how to transform that into a PHP variable and then use it in SQL QUERY. my SQL QUERY looks something like that:

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

Please explain when you answer the question thanks:)

I tried to set a variable of select form to $number. But when I tried to test it with echo I didn't get anything.I use iframe because I need page not to reload since i have some javascript functions later.

  <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>

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

DB_HOST,DB_USER,DB_PASS,DB_NAME all have the correct value since login/register works.

first of all, you are using prepared statement, so you have to initialize a stmt, prepare the statement, bind the statement with the parameter(s) and execute..

<?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
}

?>

$number = $_POST['number'];

limit = $number;

SELECT * FROM quiz_question ORDER BY RAND() LIMIT=?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM