I've created a simple customer signup form (signup.html) to capture 3 fields (email, subdomain and plan).
I also want to assign them a random password, I've lifted the code to generate this from this SO article (Generating a random password in php).
My PHP code (insert.php) is saving the form data fine into MySQL, but not the result from the randomPassword function, where it places "()" in the field instead of the randomly generated password I am hoping for.
I gather I'm not calling the result from the randomPassword() function properly. What am I doing wrong here?
SIGNUP.HTML
<form action="insert.php" method="post" class="inline-form">
<div class="form-group">
<label for="email">Your email address</label>
<input type="email" name="email" class="form-control input-lg" id="email" placeholder="Enter email">
</div><br><br>
<label>Select your plan</label><br>
<div class="radio">
<label>
<input type="radio" name="plan" id="plan" value="optionA" checked>
Option A
</label>
</div><br>
<div class="radio">
<label>
<input type="radio" name="plan" id="plan" value="optionB">
Option B
</label><br><br>
</div>
<div class="form-group">
<label for="subdomain">Pick your subdomain
</label>
<input type="text" name ="subdomain" class="form-control input-lg" id="subdomain">
</div>
<br><br>
<button type="submit" class="btn btn-teal" name="Sign Up">Sign me up!</button>
</form>
INSERT.PHP
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES
('$_POST[email]','$_POST[plan]','$_POST[subdomain]','$randomPassword()')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>