0

I'm new to PHP and I need a bit of an assistance. I'm pretty sure that this has probably been one of the most common problems and has an easy fix but I've been trying. and I'll be so stupid about it

Alright, so here's my problem: every time I go to my localhost to try and open my PHP site It won't because I get this error every time.

"Parse error: syntax error, unexpected '$db' (T_VARIABLE) in C:\xampp\htdocs\exam\register.php on line 4"

here's my PHP code.

    <?php
    session_start()

    $db = mysqli_connect("localhost", "root", "", "authentication");

    if (isset($_POST['register_btn'])) {
        session_start();
        $username = mysql_real_escape_string($_POST['username']);
        $emailaddress = mysql_real_escape_string($_POST['emailaddress']);
        $password = mysql_real_escape_string($_POST['password']);
        $password2 = mysql_real_escape_string($_POST['password2']);

        if ($password == $password2) {
            $password = md5($password);
            $sql = "INSERT INTO users(username, email, password) VALUES ('$username', '$emailaddress', '$password')";
            mysql_query($db, $sql);
            $_SESSION['message'] = "You are now registered!";
            $_SESSION['username'] = $username;
            header("location: home.php");
        }else {
            $_SESSION['message'] = "The two passwords do not match";
        }   
    }
?>
Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
Rio Ablas
  • 59
  • 7

1 Answers1

5

You have a semicolon (;) missing in the line before that, in session_start(). That is why the parser is not able to recognize the variable $db in the next line.

session_start(); // <-- this semicolon is needed

$db = mysqli_connect("localhost", "root", "", "authentication");

But there are other problems in your code as well. You are mixing between mysql_ and mysqli_ extensions. To connect to database, you are using mysqli_connect; while to escape the strings, you are using mysql_real_escape_string and mysql_query. This will not work.

Firstly, please get rid of mysql_* extension. It has been deprecated in PHP 5 and removed completely in PHP 7.

Now, your code is open to SQL injection related attacks. Please learn to use Prepared Statements instead. You can either use mysqli or PDO for the same.

Secondly, please don't use md5 to encrypt your passwords. It is old and found to be having issues. Use standard PHP functions password_hash() and password_verify(). Do Read: Secure hash and salt for PHP passwords

Thirdly, you have called session_start() twice. Please get rid of the second session_start() function call.

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57