andy
andy

Reputation: 21

How to generate token and create a url to send to email

I am trying to write a script for a student registration page, where a student enters his/her student id and if it exists then retrieve his/her email and generate a token and insert the token into the database and then send a registration url link with token and id to the student's email..how would i get that since i am a beginner in php and mysql. where am i going wrong here?

<?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';
        }
    }
?>

Upvotes: 0

Views: 1408

Answers (1)

jeroen
jeroen

Reputation: 91742

You are binding the wrong value in the query: :token vs :email.

You should actually have 2 placeholders and bind both values.

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

And as noted correctly by @Saty, you cannot have a WHERE clause on an INSERT statement:

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

Or you might need an UPDATE statement instead of an INSERT:

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

Upvotes: 2

Related Questions