Skip to content
Advertisement

Why does the user input not append to my SQL database?

I’m developing a login/register form for my client. Right now I am working on the registration part of the form however I seem to have encountered an issue.

I am trying to append the user’s input to a database if it does not currently exist. I’m developing this functionality using PHP version 7. However, the code does not seem to append the data to the database even when telling me it has done so successfully.

Here is code:

<?php
        if($_SERVER["REQUEST_METHOD"] == "POST") {
            //define variables and set values to null
            $email = $code = "";

            //set variable values to HTML input 
            $email = $_POST['email'];
            $code = $_POST['code'];

            //check if email exists
            $stmt = $conn->prepare("SELECT userEmail FROM userDetails WHERE userEmail=?");
            $stmt->bind_param("s", $prepemail);

            //set parameters and execute
            $prepemail = $email;
            $stmt->execute();

            $result = $stmt->get_result();
            if ($result->num_rows > 0) {
                echo "email exists";
                return false;
            } else {
                //$stmt->close(); removed as per @Akintunde-Rotimi's suggestion
                //insert email into database
                $stmt = $conn->prepare("INSERT INTO userDetails (userEmail) VALUES (?)");
                $stmt->bind_param("s", $newemail);

                //set parameters and execute
                $newemail = $email;
                $stmt->execute();
                echo "New records created successfully";
            }
        }
    ?>

The code successfully connects to the database and even tells me if the user already exists. It just doesn’t add the user’s email to the database and I can’t seem to figure out why.

I have researched methods on how to insert the data into the database using prepared statements as I have done here. I’ve used W3Schools as a reference but still no luck.

Advertisement

Answer

The code doesn’t seem to have any obvious spelling errors, so have you tried to catch errors? Replace

$stmt->execute();

with

if(!$stmt->execute()) {
    trigger_error("there was an error....".$conn->error, E_USER_WARNING);
}

You can also check how many rows are affected, -1 meaning there was an error.

printf("%d Zeile eingefügt.n", $stmt->affected_rows);

Also, enabling more errors to be shown (at least for development)

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// ...
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement