-3

I create a simple code for user registration, and when user submit the data was not recorded to MySQL.

Here is my logic code

<?php
    $username = $_POST["user"];
    $password = $_POST["pass"];
    $confirmPassword = $_POST["repass"];
    $email = $_POST["email"];

    $username = stripcslashes($username);
    $password = stripcslashes($password);
    $confirmPassword = stripcslashes($confirmPassword);
    $email = stripcslashes($email);

    $con = mysqli_connect('localhost', 'root', '', 'dbtest');
    if($con->connect_error)
    {
        echo"<script type='text/javascript'>alert('connection to database failed!')</script>";
    }
    else
    {
        $query = mysqli_query($con, "INSERT INTO 'user'('Username', 'Password', 'Email') VALUES('$username', $password', '$email')");
        echo "You are successfully registered!";
    }
    $con->close();
?>

Is there something that I missed?

2 Answers2

4

You have to remove the single quotes arround the column names and table names, because mysql will interpret these as strings, not as table/column names

  $query = mysqli_query($con, "INSERT INTO `user` (Username, `Password`, Email) VALUES('$username', $password', '$email')");

Also you should use prepared Statements to prevent SQL injection.

You should ask for errors after executing SQL Statements (mysqli_error())

Userand password are reserved words in mysql. To escape These , use backticks or better rename the table and the column. For more informations about keywords read the mysql documentation

Jens
  • 67,715
  • 15
  • 98
  • 113
-2

This should work, its safer now and your passwordconfirm works.

<?php
$username        = $_POST["user"];
$password        = $_POST["pass"];
$confirmPassword = $_POST["repass"];
$email           = $_POST["email"];

$username        = stripcslashes($username);
$password        = stripcslashes($password);
$confirmPassword = stripcslashes($confirmPassword);
$email           = stripcslashes($email);

$con = mysqli_connect('localhost', 'root', '', 'dbtest');
$query = sprintf("INSERT INTO user ('Username', 'Password', 'Email') VALUES ('%s', '%s', '%s')", $username, $password, $email);

if($password == $confirmPassword)
{
    $result = mysqli_query($con, $query)
    if($result)
    {
        echo "You are successfully registered!";
    }
    else
    {
        echo "Something went wrong.";
    }
    $con->close();
}
else
{
    echo "The passwords you entered didn't match.";
}

?>

I used sprintf() to make the query and checked it with mysqli_query(). It also checks if the passwords match. Regards - Raul.

KittyCat
  • 415
  • 4
  • 9
  • 26