0

I have to give users the ability to log in for an assignment. At first, it seemed to me this script was simple enough to work, but everytime I try to log in with an existing account it gives me the "login failed" message. I don't know where my mistake lies. It's a PostgreSQL database, I'll enclose an image of it below.

<?php

require 'databaseaccess.php';
try {
$conn = new PDO('pgsql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME,DB_PASSWORD);
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "\n";
phpinfo();
die();
}

$username = $_POST['username'];
$password = $_POST['password'];
$tablename = "users";

// sql-injection counter
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$qry = $conn->prepare("SELECT * FROM $tablename WHERE userid = :username and userpass = :password");
$qry->bindParam(':username', $username, PDO::PARAM_STR, 16);
$qry->bindParam(':password', $password, PDO::PARAM_STR, 16);
$qry->execute();
$result = pg_query($qry);
$count = pg_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if ($count == 1) {

    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $username;
    header("location:logingelukt.php");
} elseif ($count = -1) {
    echo "there has been an error";
} else{
    print $count;
    echo "login failed";
}
?>

I have no problems connecting to the database, so that's not an issue, it's just that it always sees $count as something else than zero. Another oddity is that the print $count command doesn't output anything.I use the account I made with postgresql outside of the page, which is just admin:admin. Also, I'm sure the right variables are getting passed from the form.

EDIT: After using var_dump($result), as advised by kingalligator, it seems that $result is indeed NULL, thus empty. I'm gonna try using fetch() instead of pg_query().

4

3 回答 3

1

我认为问题在于您正在混合 PDO 和 pg_ 函数。

代替:

$result = pg_query($qry);
$count = pg_num_rows($result);

和:

$result = $qry->fetchAll();
$count  = count($result);

PDO 函数参考可以在这里找到:http ://www.php.net/manual/en/class.pdostatement.php

于 2013-06-05T19:06:17.473 回答
0

您可能应该在 WHERE 子句中检查您的列用户 ID。我不知道表格列,但奇怪的是'userid'有用户名:

"SELECT * FROM $tablename WHERE userid = :username and userpass = :password"

也许它导致了问题。

于 2013-06-05T18:59:54.330 回答
0

您是否确认您实际上正在从查询中获取数据?尝试这个:

var_dump($result);

确保从您的查询中返回数据。您仍然可以成功连接到数据库,但查询不会返回任何内容。

于 2013-06-05T18:58:54.600 回答