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

PHP Log In

HI,

Whats wrong with this code?

<?php

if(isset($_POST['username'])&&isset($_POST['password'])){
    $username = $_POST['username'];
    $password = $_POST['password'];

    $password_hash = md5($password);

    if(!empty($username) &&!empty($password)) {

        $query = "SELECT `id` FROM `users` WHERE `username`='$username' AND `password`='$password_hash'";
        if ($query_run = mysqli_query($query)) {
            $query_num_rows = mysqli_num_rows($query_run);

            if ($query_num_rows==0) {
                echo 'Invalid username/password combination.';
            }else if ($query_num_rows==1) {
                echo 'OK.';
            }
        }


    } else{
        echo 'You must supply a username and password.';
    }
}

?>
<form action="<?php echo $current_file; ?>" method="POST">
    Username: <input type="text" name="username">
    Password: <input type="password" name="password">
    <input type="submit" value="Log in">
</form>

It partly does if i dont enter the password. And it does work when i enter the password but without the code to the database. if i add it, then it doesnt work . Is there soemthing bad in it?

1 Answer

There is no datebase connection.

Shoudnt this work?

INDEX PAGE:

<?php
require 'core.inc.php';
require 'connect.inc.php';
include 'loginform.inc.php';


?>

Try adding the connect require in the login form file.

What i did is like you said there is no database connection , what i thought to do it to put the variable of connection to the database here

if ($query_run = mysqli_query($con, $query)) {
            $query_num_rows = mysqli_num_rows($query_run);

I added $con. Thank you. Hopefuly it will work later xd

So it works?

Yes. Thank you!

Awesome glad to help. Im not even a php developer. haha

Well, the fact of giving the " database connection" i knew allready what im missing. I believe thats rigth. Thank you. ^^ maybe you ment something different but sure it helped :)

I just noticed there nothing for the query to refer to I have built php stuff before but I read it well just cant write it.

You need more practice xd