Nate
Nate

Reputation: 355

How to get started debugging a PHP script

I am pretty new to PHP, so debugging isn't really something I am familiar with when it comes to PHP.

I am using php/javascript(ajax) to change a users password for my website. So basically, when I log in and try to change my password. The code breaks at the first echo. So the password that I am entering into the form does not match the password in the database. But, I am using the same hash method and everything. If anyone has any ideas, let me know. Thanks!

if(isset($_POST["u"])) {
    $u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
    $oldpasshash = md5($_POST["cp"]);
    $newpasshash = md5($_POST["cnp"]);
    $sql = "SELECT id, username, password FROM users WHERE username='$u' LIMIT 1";
    $query = mysqli_query($db_conx, $sql);
    $row = mysqli_fetch_row($query);
    $db_id = $row["id"];
    $db_username = $row["username"];
    $db_password = $row["password"];
    if($db_password != $oldpasshash){
        echo "no_exist";
        exit();
    } else {
        $sql = "UPDATE users SET password='$newpasshash', WHERE username='$db_username' LIMIT 1";
        $query = mysqli_query($db_conx, $sql);
    }
    $sql = "SELECT id, username, password FROM users WHERE username='$db_username' LIMIT 1";
    $query = mysqli_query($db_conx, $sql);
    $row = mysqli_fetch_row($query);
    $db_newpass = $row[3];
    if($db_newpass == $newpasshash) {
    echo "success";
    exit();
    } else {
        echo "pass_failed";
        exit();
    }
}

Upvotes: 1

Views: 64

Answers (2)

Pitchinnate
Pitchinnate

Reputation: 7556

Look at your first two lines of code:

if(isset($_POST["u"])) {
    $u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);

You check if $_POST['u'] isset then you use $_GET['u'].

FYI, you are injecting $u directly into the mysql statement, don't do this.

Upvotes: 1

fortune
fortune

Reputation: 3372

You are using mysqli_fetch_row and accessing the table fields via field name. That is wrong.

mysqli_fetch_row fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero).

So you have to use

$db_id = $row[0];
$db_username = $row[1];
$db_password = $row[2];

Upvotes: 1

Related Questions