Reputation: 95
I want to check if a user (email) ist already in the database or not.
$email_pruefen = ($_GET['email']);
//SQL Statement ob email bereits existiert
try {
$stmt = $pdo->prepare("SELECT rechnungsmail FROM kundendaten WHERE rechnungsmail = :checkmail");
$stmt->execute([':checkmail' => $email_pruefen]);
$fetchergebnis = $stmt->fetchAll(); //entnimmt alles aus dem Statement (Value, True/False, ..)
if($fetchergebnis[0] > 0){
$ergebnis = "Ja"; //Eintrag ist vorhanden
} else {
$ergebnis = "Nein"; //Eintrag ist nicht vorhanden
}
$pdo = null; //Verbindung schließen
} catch (PDOException $e) {
$meldung_checkemail = "Überprüfung der E-Mail Adresse war ohne Erfolg. Bitte wenden Sie sich an die IT.";
echo "<script type='text/javascript'>alert('$meldung_checkemail');</script>";
die();
}
if($ergebnis == "Nein"){ //Wenn Email nicht existiert, führe folgendes aus
... create user ...
}else{
... dont create user ...
}
If there is no existing entry, the user can create it.
but my code dont work :I any ideas?
Upvotes: 0
Views: 69
Reputation: 5401
I tested if($fetchergebnis[0] > 0)
using var_dump()
, and it seems that this returns a Undefined offset:0
plus bool(false)
when the statement fetched nothing (tested it because I never tried using it before)
One way is to use rowCount()
before fetching to check if any row has been returned by the SELECT
statement, something like this:
$stmt = $pdo->prepare("SELECT rechnungsmail FROM kundendaten WHERE rechnungsmail = :checkmail");
$stmt->execute([':checkmail' => $email_pruefen]);
$ergebnis = ($stmt->rowCount() > 0) ? 'Ja' : 'Nein';
OR
Since you are just checking if something exist and not needing to use any data fetched from it, you can also use COUNT(*)
:
$stmt = $pdo->prepare("SELECT COUNT(*) FROM kundendaten WHERE rechnungsmail = :checkmail");
$stmt->execute([':checkmail' => $email_pruefen]);
$count = $stmt->fetchColumn();
$ergebnis = ($count > 0) ? 'Ja' : 'Nein';
Upvotes: 1
Reputation: 157880
Your problem is that your are comparing a string (email) with a number (0). In this case a string will be converted to a number and become 0. 0 is not bigger than 0, so your condition returns false
Use just $fetchergebnis
in your comparison and it would work. PHP is a loosely typed language, you can use a variable of almost any type in a conditional operator and any "non-empty" value wold work as true
. A non-empty array as well.
Better yet, instead of fetchAll()
which is unsuitable for this case, use a more appropriate fetchColumn()
(but nevertheless check the direct result, the actual variable you get from fetch)
A canonical solution for your task: How to check if email exists in the database?
Upvotes: 4