2

我有一个应用程序,你可以在这里查看。当您打开应用程序时,您会看到一个提交按钮,只需单击该按钮,您就会看到它会在下面生成字符串。如果您继续单击该按钮,它会在字母“A”和“B”之间生成 2 个字母字符串。

如果在“SessionId”列下的数据库中,我有一行字符串“AB”。然后,当我继续单击提交按钮时,它不会生成字符串“AB”。我已经对此进行了测试,并且效果很好。因此,如果字符串末尾不包含数字,这不是问题。

我遇到的问题是这个。如果我想创建多个考试。假设字符串是“AA”并且我有 3 个考试,它不会在数据库中插入字符串“AA”,因为有多个“AA”,所以它在数据库中的每个“AA”之后连接一个数字,这样它显示为“AA1”、“AA2”和“AA3”。

但问题是,如果它这样做了,那么当您再次使用该应用程序并继续单击“提交”按钮时,您会看到它仍然会生成字符串“AA”,因为它不应该这样做,因为字符串“AA”被用于数据库为“AA1”、“AA2”和“AA3”。我目前在数据库中有这三个值,但它仍然在应用程序中生成字符串。

所以我的问题是,如果字符串在数据库中并且末尾连接了一个数字,我该如何阻止它在应用程序中生成字符串?

下面是应用程序的代码:

<?php

 // connect to the database
 include('connect.php');

  /* check connection */
  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    die();
  }


function id_generator(){ 

          $id = ""; 
          $a = array( "A" , "B", "C" ); 

      for( $i = 0 ; $i < 2 ; $i++ ){ $r = rand( 0 , 1 );
       $id .= $a[ $r ]; 

   }

   return $id;

   };

   $is_there = true;

      while( $is_there ){
    $id = id_generator(); // your function to generate id;
    $result = "SELECT SessionId FROM Session WHERE SessionId LIKE CONCAT(?, '%')";

    $stmt=$mysqli->prepare($result);
    // You only need to call bind_param once
    $stmt->bind_param("1",$id);
    // execute query
    $stmt->execute(); 
    // get result and assign variables (prefix with db)
    $stmt->bind_result($dbSessionId);

    $stmt->store_result();

    $stmtnum = $stmt->num_rows();

    if($stmtnum == 0) {
    $is_there = false;
}
}

 ?>

    <h1>CREATING A NEW ASSESSMENT</h1>

        <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
        <p>
        <input id="courseSubmit" type="submit" value="Submit" name="submit" />
        </p>
        </form>

        <?php
if (isset($_POST['submit'])) {

        ?>




        <br/>

         <form action="QandATable.php" method="post" id="sessionForm">
         <p><strong>1: Your Assessment ID: </strong><span id="idFont"><?php echo $id; ?></span></p>
         <input type='hidden' name='id' value='<?php echo $id; ?>' />


        </form>



        <?php

        }
        ?>

    </body>
</html>
4

1 回答 1

1
// You only need to call bind_param once
$stmt->bind_param("1",$id);

将其更改为:

// You only need to call bind_param once
$stmt->bind_param("s",$id);

bind_param 函数的第一个参数告诉解析器它是什么类型的参数(即字符串、int 等): http: //php.net/manual/en/mysqli-stmt.bind-param.php

于 2012-11-05T01:38:45.797 回答