TripleDeal TripleDeal - 6 months ago 19
PHP Question

Login script doesn't work

I'm working on a login script, but it doesn't let me sign in even though the account information are correct. I've used this login script in the past, but it used MySQL, so I changed a couple of things so I would work with MySQLi, but it doesn't.


$con = mysqli_connect("localhost","root","wachtwoord","huizenverkoop");

// Database verbinding controleren
if (mysqli_connect_errno()){
echo "Kan geen verbinding maken met MySQL: " . mysqli_connect_error();

Updated: login.php

include 'config.php';

header("Location: index.php");
$gebruikersnaam = mysqli_real_escape_string($con, $_POST['gebruikersnaam']);
$wachtwoord = mysqli_real_escape_string($con, $_POST['wachtwoord']);

$gebruikersnaam = trim($gebruikersnaam);
$wachtwoord = trim($wachtwoord);

$query = "SELECT id, gebruikersnaam, wachtwoord FROM persoon WHERE gebruikersnaam='$gebruikersnaam'";
$row = mysqli_query($con,$query);

$count = mysqli_num_rows($row);

if($count == 1 && $row['wachtwoord']==md5($wachtwoord)){
$_SESSION['persoon'] = $row['id'];
header("Location: index.php");
header("Location: login.php?fout=true");

if (@$_GET['fout'] == 'true'){
$melding = "De ingevulde gegevens kloppen niet.";

Gebruikersnaam means username and wachtwoord means password. When I press the button "log in" it sends me to login.php?fout=true. Fout means wrong.

<form method="post">
<h1 class="box-titel">Inloggen</h1>
<div class="controle">
<input type="text" class="speciaal-tekstveld" name="gebruikersnaam" placeholder="Gebruikersnaam" required>
<input type="password" class="speciaal-tekstveld" name="wachtwoord" placeholder="Wachtwoord" required>
<input type="submit" class="grootknop" name="loginnu" value="Inloggen">

Persoon table:

id int(2)
gebruikersnaam varchar(50)
wachtwoord varchar(255)

Could someone please help me?


You'll need to fetch the data, not just query it. You currently are trying to use a MySQLi object, which is the result from the query, this isn't an array with the data from the database, it needs to be fetched first. You'll need something like this

$query = "SELECT id, gebruikersnaam, wachtwoord FROM persoon WHERE gebruikersnaam='$gebruikersnaam'";
$result= mysqli_query($con,$query);
$row = mysqli_fetch_assoc($result); // Fetch the data!
$count = mysqli_num_rows($result);

if($count == 1 && $row['wachtwoord']==md5($wachtwoord)){
     // ....

You can also check for the password in the query, reducing some of your code. Basically, if you can do something in SQL, do it in SQL.

In addition to this, you shouldn't use md5 for storing passwords. PHP has a built-in password_hash() function which is a lot more secure!

You should also take advantage of using prepared statements, to protect your database against SQL-injection attacks.

Reading-material & documentation