簡體   English   中英

試圖在MySQL中保存PHP函數的結果

[英]Trying to save result from PHP function in MySQL

我創建了一個簡單的客戶注冊表單(signup.html)來捕獲3個字段(電子郵件,子域和計划)。

我還想為他們分配一個隨機密碼,我已經提取了代碼來生成這篇SO文章( 在php中生成一個隨機密碼 )。

我的PHP代碼(insert.php)將表單數據保存到MySQL中,但不是randomPassword函數的結果,它在字段中放置“()”而不是我希望的隨機生成的密碼。

我收集我沒有正確調用randomPassword()函數的結果。 我在這做錯了什么?

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);
?>

它看起來不像你指定一個變量來包含密碼。 函數不僅僅是自己執行。 使用以下內容:

$myPass=randomPassword();

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

它自己的一個功能就是坐在那里等待執行,但不會自行啟動。 在這種情況下,函數返回一個值(它所做的密碼)。 要實際獲得它,你可以編寫類似$myPass=randomPassword();代碼$myPass=randomPassword(); 然后執行該函數,並將值傳遞給變量。

由於你似乎不是一個老將,我會擴展一些。 如果您不確定為什么要使用函數而不是僅僅執行代碼,則可以反復使用函數。 讓我們說我做了以下事情:

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

有了這個功能,我現在在變量中存儲了兩個完全不同的密碼。 你可以做各種其他花哨的事情,但是把一個函數想象成一段代碼片段,可以在你的代碼中重復使用,希望在很多場合 - 不需要多次編寫代碼。

也許這會奏效

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM