Pregunta

When I use the code below I get Undefined Index: email on $row['email']. If I grab the whole array with $row and print_r, it displays like it should. Where am i going wrong ?

            $stmt = $db->dbh->prepare("SELECT email FROM $this->table WHERE `email`= :email");
            $stmt -> bindValue(':email', $email);
            $stmt->execute();
            while ($row = $stmt->fetchAll()){
                 return $row['email'];
              }

$new = new Users;
 echo $new->reset_password($email);
}
¿Fue útil?

Solución

fetchAll returns a 2-dimensional array of all the results. To get just one row at a time, you should call $stmt->fetch(), not $stmt->fetchAll().

while ($row = $stmt->fetch()) {
    ...
}

But since you're returning, you shouldn't use a loop at all. The return statement will terminate the loop after the first iteration. Just use an if statement.

if ($row = $stmt->fetch()) {
    return $row['email'];
}

This whole code doesn't make much sense -- $newemail is guaranteed to be the same as $email, why are you returning it? It probably should be:

if ($stmt->fetch()) { // Email was found
    return true;
} else {
    return false;
}

Otros consejos

to check if the email entered in the db,

$stmt = $db->dbh->prepare("SELECT 1 FROM $this->table WHERE email= ?");
$stmt->execute([$email]);
return $stmt->fetchColumn();

You should use this code:

while ($row = $stmt->fetch()){
    $newemail = $row['email'];             
}

Instead of this code:

while ($row = $stmt->fetchAll()){
    $newemail = $row['email'];
}

Method fetchAll() fetches all rows in a single call, method fetch() fetches only current row and moves pointer to the next row.

Documentation to method fetch() can be found here and documentation to method fetchAll can be found here.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top