如果已经在数据库中,则不希望生成字符串

时间:2012-11-02 13:29:13

标签: php mysql

我这里有一点情况。如果我在“会话”表中的数据库中,如果我有以下数据:

SessionId

C

然后我的代码会发生的情况是,当用户生成一个新字符串时,它不会显示上面的字符串,因为它已经存在于数据库中。这很好,例如上面。

我遇到的问题是,如果我有多个会话(考试),那么在下面的数据库中它将在数据库中显示如下字符串:

SessionId

C1
C2
C3

以上是3门考试。但问题是字符串“C”仍然可以在下面的代码中生成。我的问题是,如果字符串末尾有一个数字,如上表,那么我怎么能不生成字符串,因为它仍然在数据库中?字符串总是1个字符长:

          function id_generator(){ 

              $id = ""; 
              $a = array( "A" , "B" , "C" , "D" , "E" , "F" , "G" , "H" , "I" , "J" , "K" , "L" , "M" , "N" , "O" , "P" , "Q" , "R" , "S" , "T" , "U" , "V" , "W" , "X" , "Y" , "Z" ); 

          for( $i = 0 ; $i < 1 ; $i++ ){ $r = rand( 0 , 25 );
           $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 ?";
        $stmt=$mysqli->prepare($result);
        $id = $id . '%';
        $stmt->bind_param("s",$id);
        $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;
    }
    }

....

</body>
<form>

 <p><strong>1: Your Assessment ID: </strong><span id="idFont"><?php echo $id; ?></span></p>

....

2 个答案:

答案 0 :(得分:1)

为什么不使用like

$result = "SELECT SessionId FROM Session WHERE SessionId LIKE ?";
$stmt=$mysqli->prepare($result);
$id = $id . '%';
$stmt->bind_param("s",$id);

答案 1 :(得分:0)

不确定我能得到你,但也许是

if not Exists(Select * From Session Where SessionID Like 'C[0123456789]')
begin
  insert Session(SessionID) Values(?)
end

'C [0123456789] isa straing以C开头,然后是'0'到'9'的任何人,没有别的