I am trying to output randomly generated values via "echo" command and write them to a database. The "echo" output is no problem, but in the mySQL table only the first digit of the generated number is given. In theory there should be displayed five digits. https://i.stack.imgur.com/1KPGi.png
if ($submitbutton){
$length = 5;
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@#$&*";
$size = strlen( $chars );
echo "Key: ";
for( $i = 0; $i < $length; $i ) {
$str= $chars[ rand( 0, $size - 1 ) ];
echo $str;
$sql = "INSERT INTO regkey (regkey) VALUES (?)";
$stmt = mysqli_prepare($link, $sql);
$str1 = $str;
mysqli_stmt_bind_param($stmt, "s", $str1);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
}
If I try to enter another predefined value via php, this works without problems.
CodePudding user response:
This is nothing to do with your database.
In your for
loop, you overwrite $str
with a single character every time the loop runs. I guess you intended to append to it instead using .=
. (N.B. This logical flaw is masked by the fact you echo within the loop, so on screen you see what looks like a single string but is in fact 5 separate strings right next to each other.)
You then also run the INSERT the same number of times, so you get 5 separate entries, one for each digit (although since you close the connection within the loop and then don't re-open it, it's hard to see how that is actually succeeding - I'd guess the 2nd query fails and you either didn't mention the error or have suppressed all error reporting so you didn't see it).
It was little unclear, but I think you wanted to generate one 5-digit string and write it all to the same row in the database? If so, then do it like this:
if ($submitbutton){
$length = 5;
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@#$&*";
$size = strlen( $chars );
echo "Key: ";
$str = "";
for( $i = 0; $i < $length; $i ) {
$str .= $chars[ rand( 0, $size - 1 ) ]; //append not overwrite
}
//after the loop has finished, do the echo and insert once only
echo $str;
$sql = "INSERT INTO regkey (regkey) VALUES (?)";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "s", $str);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
N.B. As suggested in the comments, you could also replace the for
loop entirely with
$str = substr(str_shuffle($chars), 0, $length);
which will do the same job for you using existing PHP functions.