我创建了一个简单的客户注册表单 (signup.html) 来捕获 3 个字段(电子邮件、子域和计划)。
我还想为他们分配一个随机密码,我已经从这篇 SO 文章(在 php 中生成随机密码)中提取了生成此密码的代码。
我的 PHP 代码 (insert.php) 将表单数据保存到 MySQL 中,但不是 randomPassword 函数的结果,它在字段中放置“()”,而不是我希望的随机生成的密码。
我收集我没有正确调用 randomPassword() 函数的结果。我在这里做错了什么?
注册.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>
插入.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);
?>