Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

Loop through all records or search for one specific record when checking if email exists

I seem to be confusing myself today for some reason.

The user has the ability to change their email address. When they type in a new email address I need to check the database to see if that email address exists.

Should I loop through records like this?

if($numRows > 0) {
while($row = $result->fetch_assoc())  {
if ($_POST['new_email'] == $row['user_email'])  {
echo "<div class='alert alert-danger'>Sorry, that email address is not available.</div>";
	    }
	}
}

Open in new window


Or should I look for one specific record ( I think that is the difference between the two if I understand correctly)?

$result = $stmt->get_result();
if($result) {
$row = $result->fetch_assoc();
}

Open in new window


Or does it not really make much difference?
SOLUTION
Avatar of Mukesh Yadav
Mukesh Yadav
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Crazy Horse

ASKER

Sorry, I realized I am doing it again, not posting enough code.

This was the while loop method:

$new_email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$stmt = $link->prepare("SELECT `user_email` FROM `users` WHERE `user_email` != ?");
$stmt->bind_param("s", $_SESSION['user_email']);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
while($row = $result->fetch_assoc()) {


if ($_POST['email] == $row['user_email']) {

echo "<div class='alert alert-danger'>Sorry, that email address is not available.</div>";

Open in new window

@ Mukesh Yadav,

In phpMyadmin I have the email column set to UNIQUE. Are you saying I should also set it to INDEX?
And for some reason, this code echo's out "found a result" even if there is no match in the database.

$new_email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$stmt = $link->prepare("SELECT `user_email` FROM `users` WHERE `user_email` = ?");
$stmt->bind_param("s", $new_email);
$stmt->execute();
$result = $stmt->get_result();
if($result) {			
echo "found a result";
}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial