Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

James Barrett
James Barrett
13,253 Points

How to display an error message if the email or password is incorrect (MYSQLi and PHP)

Hi there,

I am currently making a login system and I am not sure how to implement an error message if the user enters the wrong credentials. Here is my code so far (which I followed of a YouTube tutorial:

  if(isset($_POST['submit'])) {
    $email = $_POST['user_email'];
    $password = $_POST['user_password'];

    $result = $db->query("SELECT * FROM User WHERE U_Email='$email' AND      U_Password='$password'");

    $row = $result->fetch_array(MYSQLI_BOTH);

    session_start();

    $_SESSION["U_ID"] = $row['U_ID'];
    $_SESSION["U_Forename"] = $row['U_Forename'];

    header('Location: dashboard.php');
  }

I am not sure where to begin. Furthermore, what exactly is this line doing:

$row = $result->fetch_array(MYSQLI_BOTH);

The tutorial does not really go into detail about it. I want to ensure I understand everything!

Thanks, James.

Matthew Smart
Matthew Smart
12,567 Points

From the look of the code, I would learn from somewhere else that actually explains things to you.

  1. The biggest problem with the code above is the fact you do not escape the submitted values. This will mean that you are open to SQL injection and getting hacked. http://www.w3schools.com/sql/sql_injection.asp

  2. Further more you are saving the user password into the database without any encryption which is vital. This means that if you are subject to SQL injection from the previous problem, then the hacker will have access to every single username and password in your database. http://php.net/manual/en/faq.passwords.php

To answer your question, the line of code means to fetch a result row as an associative array, a numeric array or both. http://php.net/manual/en/mysqli-result.fetch-array.php

If you do not understand these terms, I would say that your maybe jumping ahead of your self in hopes that you can throw bits of code together and make a finished product. Depending on the application your making following in the same direction your going will leave the door open to malicious attacks.