如何生成令牌并创建要发送到电子邮件的网址

时间:2016-05-10 07:50:20

标签: php mysql pdo

我正在尝试为学生注册页面编写脚本,学生输入他/她的学生ID,如果存在,则检索他/她的电子邮件并生成令牌并将令牌插入数据库然后发送注册网址链接与令牌和ID到学生的电子邮件..我会得到,因为我是PHP和MySQL的初学者。 我在哪里错了?

<?php
    error_reporting(1);
    session_start();
    include 'includes/connect.php';
    include 'includes/tokengenerator.php';
    if ($_POST["Submit"] == "Submit") {
        $stu_id = $_POST['stu_id'];
        $sql = "SELECT email FROM people WHERE stu_id = :stu_id";
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':stu_id', $stu_id);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!empty($result)) {
            $email = $result['email'];
            //echo $email;
            //exit();
            for ($i = 1; $i <= 2; $i++) {
                $token = generateToken();
                //echo $token;
                $email = $result['email'];
                $sql = "INSERT INTO students (token) VALUES ($token) WHERE email = :email";
                $stmt = $pdo->prepare($sql);
                $stmt->execute(array(
                    ':token' => $token,
                ));
                $result1 = $stmt->fetch(PDO::FETCH_ASSOC);
            }
        } else {
            echo 'Please Contact principal for student ID';
        }
    }
?>

1 个答案:

答案 0 :(得分:2)

您在查询中绑定了错误的值::token vs :email

您实际上应该有2个占位符并绑定两个值。

<击>

<击>
$sql = "INSERT INTO students (token) VALUES (:token) WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
     ':token' => $token,
     ':email' => $email
));

<击>

正如@Saty正确指出的那样,WHERE声明中没有INSERT条款:

$sql = "INSERT INTO students (token, email) VALUES (:token, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
     ':token' => $token,
     ':email' => $email
));

或者您可能需要UPDATE语句而不是INSERT

$sql = "UPDATE students SET token = :token WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
     ':token' => $token,
     ':email' => $email
));