0

I need a second pair of eyes to have a look at my code and tell me what I am missing, as I think I have identified the portion of code that doesn't work, I just don't know why.

Basically I am trying to register a user to a database, in a way that it prevents SQL injection. For the life of me however, it doesn't work. When I deconstruct the code and make it less secure, it works. Anyway, code is here:

//require_once 'sendEmails.php'; 
session_start();
$username = "";
$email = "";
$user_dob = "";
$user_fname = "";
$user_lname = "";
$user_telephone = "";
$errors = [];
$servername = '';
$login = '';
$password = '';
$DBname = '';
$rows = 0;
$query = "";


$conn = new mysqli($servername, $login, $password, $DBname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($conn) {
  echo "Connected successfully";
}

// SIGN UP USER
if (isset($_POST['signup-btn'])) {
    if (empty($_POST['username'])) {
        $errors['username'] = 'Username required';
    }
    if (empty($_POST['email'])) {
        $errors['email'] = 'Email required';
    }
    if (empty($_POST['password'])) {
        $errors['password'] = 'Password required';
    }
    if (isset($_POST['password']) && $_POST['password'] !== $_POST['passwordConf']) {
        $errors['passwordConf'] = 'The two passwords do not match';
    }
    if (empty($_POST['dob'])) {
        $errors['dob'] = 'Date of birth required';
    }
    if (empty($_POST['fname'])) {
        $errors['fname'] = 'First name required';
    }
    if (empty($_POST['lname'])) {
        $errors['lname'] = 'Last name required';
    }
    if (empty($_POST['telephone'])) {
        $errors['telephone'] = 'Telephone number required';
    } //--checks input in browser

    //I think it works untill this point...

    $token = bin2hex(random_bytes(50)); // generate unique token
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_BCRYPT); //encrypt password
    $user_dob = $_POST['dob'];
    $user_fname = $_POST['fname'];
    $user_lname = $_POST['lname'];
    $user_telephone = $_POST['telephone'];
    $email = $_POST['email'];

    //Above assigns inputted values into variables declared at the start

    //echo $token, $email; //-- this works
    //nl2br() ; // -- line break in php

    // Check if email already exists
    //$result = $mysqli->query("SELECT * FROM User_tbl WHERE email='$email' LIMIT 1");



    $sql = "SELECT * FROM User_tbl WHERE email='$email' LIMIT 1";
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > $rows) {
              $errors[] = $email;
        echo "Email already exists";
    }

    $errorsInt = count($errors);
    echo mysqli_num_rows($result);
    echo count($errors);
    echo $errorsInt;

    if ($errorsInt === $rows) {
        $query = "INSERT INTO User_tbl SET token=?, username=?,  password=?, user_dob=?, user_fname=?, user_lname=?, user_telephone=?, email=?";
      // "INSERT INTO User_tbl VALUES (?, ?, ?, ?, ?, ?, ?, ?)"

        echo $query;
    //---------------------------------------------------------------------------

        $stmt = $conn->prepare($query); //first
        $stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
        $result = $stmt->execute();

        echo $result;

            if ($result) {
                $user_id = $stmt->insert_id;
                $stmt->close();

                $_SESSION['id'] = $user_id;
                $_SESSION['username'] = $username;
                $_SESSION['email'] = $email;
                $_SESSION['verified'] = false;
                $_SESSION['message'] = 'You are logged in!';
                $_SESSION['type'] = 'alert-success';
                header('location: index.php');
            } else {
                $_SESSION['error_msg'] = "Database error: Could not register user";
            }
        }


}

The problem I believe starts here:

$stmt = $conn->prepare($query); //first
        $stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
        $result = $stmt->execute();
Gregory Sky
  • 140
  • 9
  • Are you getting an error when you try to insert? – Barmar May 08 '20 at 21:22
  • When the insert fails, you should print `$stmt->error` to see the reason. – Barmar May 08 '20 at 21:23
  • 3
    Or add mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); add the start of your code but even better USE PDO – Frank B May 08 '20 at 21:23
  • I'm with Frank, use PDO. You can also see last error by calling mysqli_error() so put that at the end of your code perhaps, as a temp measure – Jason Stephenson May 08 '20 at 21:25
  • You are using `'sssissis'` as types for the bound values. Are you sure there are two integers in there? Dates should be entered as strings, e.g. `'2020-05-08'`, and the same for phone numbers. Check your table schema. – jotaelesalinas May 08 '20 at 21:34
  • Are these your real database credentials? – Dharman May 08 '20 at 21:46
  • Please enable error reporting and then tell us what errors if any are you getting. [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman May 08 '20 at 21:49
  • I recommend changing these credentials right now. Removing them from the post is not going to help, because we have all seen it already. – Dharman May 08 '20 at 21:56
  • yeah my bad. goign to change them now. fortunatelly there is nothing of value, its a testing server – Gregory Sky May 08 '20 at 21:58
  • i changes types all to string which hasnt changed anythign. What i get is, there is nothing written to a DB and there are no errors, page refreshes itself, passwords dissapear and thats it. Why is everyone advising PDO? – Gregory Sky May 08 '20 at 21:59
  • Because mysqli is terrible. PDO is easier and works much better. – Dharman May 08 '20 at 22:00
  • I don't think we can help you much other than telling you to put `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` at the top of your code. There is too much code in the question and not enough at the same time. We need [mcve]. We do not see the HTML form and we do not up to which point your code executes fine. Do you have a debugger installed? Have you stepped line by line through the code? Does it ever reach the prepared statement? – Dharman May 08 '20 at 22:03
  • I stated that in the post, i have been through the code ;line by line, and everything executes to the point where ->look second snippet. Also cannot make any changes right now, servers taken down for maintenance till Tuesday.... but thanks anyway everyone, Ill try PDO! – Gregory Sky May 08 '20 at 22:06
  • If this is where the code stops then you should see an exception. – Dharman May 08 '20 at 22:11
  • It doesnt show any errors... thats the problem, i dont see any feedback and it doesnt work... anyway, as i said in the previous comment, ill try again on Tuesday. Cheers! – Gregory Sky May 08 '20 at 22:13

0 Answers0