I have a login database with user and password and a html file with input type for username and password..
in my class for the login:
class login
{
protected $_username;
protected $_password;
public function __construct($username, $password) //$username and $password values will be from the $_POST['username and password'] when the user submits the username and password
{
$this->username = $username;
$this->password = md5($password);
}
public function login()
{
try {
$pdo = dbConnect::getConnection();
$smt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$smt->bindParam(1, $this->username);
$smt->execute();
echo "
";
print_r($smt->fetch(PDO::FETCH_OBJ)); //testing if $smt will return results..yes it returned
if($smt->fetch()) {
print_r($smt->fetch(PDO::FETCH_OBJ)); //doesn't return ??this is my question... all other arguments inside this if loop is not executed..
while($row = $smt->fetch(PDO::FETCH_OBJ)) {
echo "one";
if($row->password == $this->password) {
header("Location: admin.php");
}
else {
echo '
Error!
username and password do not match!}
}
}
else {
echo '
Error!
Username does not exist!}
}
catch (PDOException $e) {
die($e->getMessage());
}
}
}
the problem is that in PDO, it will not return data that i've been requesting after the if($smt->fetch()) which is used to know if the query returned a result.. before the fetch, the print_r returns data... i can't continue my code because of this..im new to OOP and PDO that's why i can't handle this unlike from mysql or mysqli functions.. im new to PDO, also im using sqlite here..
解决方案
You're fetching multiple times:
print_r($smt->fetch(PDO::FETCH_OBJ)); //testing if $smt will return results..yes it returned
if($smt->fetch()) {
print_r($smt->fetch(PDO::FETCH_OBJ)); //doesn't return ??this is my question... all other arguments inside this if loop is not executed..
while($row = $smt->fetch(PDO::FETCH_OBJ)) {
Each of these lines will try to fetch the next row from the returned data. But your query looks like it only returns one row. This row will be printed by the first print_r(). Then when you fetch again in if(), there won't be anything left, so it will return false and the if will fail.
You can use $smt->fetchAll() to return all the results in an array. You can then test whether this array has any elements, and loop through it to print the results.
$results = $smt->fetchAll(PDO::FETCH_OBJ);
if (count($results)) {
foreach ($results as $row) {
print_r($row);
if($row->password == $this->password) {
header("Location: admin.php");
}
else {
echo '
Error!
username and password do not match!}
}
}
else {
echo '
Error!
Username does not exist!}
Although I don't understand why you're using a loop when you can be pretty sure the query will never return more than 1 row. I see this all the time, I don't understand it, unless programmers are simply copying code from other queries that return multiple rows, and they don't understand that the loop is unnecessary.