尝试在 MySQL 中保存 PHP 函数的结果


Trying to save result from PHP function in MySQL

我创建了一个简单的客户注册表单(注册.html)来捕获3个字段(电子邮件,子域和计划)。

我还想为他们分配一个随机密码,我已经从这篇 SO 文章中提升了代码以生成这个(在 php 中生成随机密码)。

我的PHP代码(insert.php)将表单数据很好地保存到MySQL中,但不是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);
?>

看起来您根本不分配变量来包含密码。函数不只是自行执行。使用以下内容:

$myPass=randomPassword();
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES
('$_POST[email]','$_POST[plan]','$_POST[subdomain]','$myPass')";

它自己的函数只是坐在那里等待被执行,但不会自行触发。在这种情况下,该函数返回一个值(它创建的密码)。为了实际获取它,您编写像$myPass=randomPassword();这样的代码,然后执行函数并将值传递到变量中。

由于你似乎不是老手,我会再扩展一些。如果您不确定为什么要拥有一个函数而不是首先执行代码,则可以一遍又一遍地使用函数。假设我做了以下操作:

$myPass1=randomPassword();
$myPass2=randomPassword();

有了这个函数,我现在在变量中存储了两个完全不同的密码。你可以做各种其他花哨的事情,但把函数想象成一个代码片段,可以在你的代码中重用,希望在很多场合 - 不需要多次编写它。

也许这会起作用

$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES ('$_POST[email]','$_POST[plan]','$_POST[subdomain]','randomPassword()')";