I have a application which you can view here. When you open the app, you will see a submit button, simply click on the button and you will see that it will generate string underneath. If you keep clicking on the button it keeps generating 2 letter strings between letters “A” and “B”.
If in the database under the “SessionId” column, I have in a row string “AB”. Then it would not generate string “AB” when I keep clicking on the submit button. I have tested this and this works fine. So this is not an issue if the string contains no number at the end.
The problem I have is this. If I want to create multiple exams. Lets say the string is “AA” and that I have 3 exams, it does not insert string “AA” in the database as there are multiple “AA”, so instead it concatenate a number after each “AA” in the database so that it displays it as “AA1”, “AA2” and “AA3”.
But the problem is that if it does this then when you use the app again and keep clicking on the “Submit” button, you see that it still generates string “AA” when it shouldn’t do as string “AA” was used in the database as “AA1”, “AA2” and “AA3”. I have these three values in the database at the moment yet it still generates the string in the application.
So my question is that how can I stop it from generating the string in the application if the string is in the database with a number concatenated at the end of it?
Below is the code for the application:
<?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>
Change this to:
The first argument of the bind_param function tells the parser what type of parameter it is (ie. string, int etc): http://php.net/manual/en/mysqli-stmt.bind-param.php