Jump to content

Redirect if record already exists in database


ramone_johnny

Recommended Posts

I have the following snippet of code that I *think* is right, but being new to PHP I just wanted if someone could let me know if this is indeed correct.

 

I'm simply redirecting the user if they are already a member (email exists in the db)

$r=query_wrapper("SELECT * FROM tblmembers WHERE mem_email = ?",$mem_email);
$rstDBEdit=mysql_fetch_assoc($r);

if($rstDBEdit)
redirect("/message.php?message=already_a_member");

if ($stmt = mysqli->prepare("SELECT * FROM tblmembers WHERE mem_email=? LIMIT 1")) {
$stmt->bind_param("s", $mem_email);
$stmt->execute();
$stmt->store_result();
$count=$stmt->num_rows;
$stmt->close();
}
// If count is greater than 0 then you know email exists:
if ($count) {
header("index.php");
exit;
}


there's nothing functionally wrong with your code because mysql_fetch_assoc($r); will return a false value if the query did not match any row (or if the query failed due to an error). this also assumes that your redirect() function executes an exit/die statement after the header() redirect to prevent your code from continuing to run.

 

however, if you are not going to use the actual data from the query and just need to find out if there's a matching row(s) with some value, it is more desirable to use COUNT() in a query, then get and test that count value -

$r=query_wrapper("SELECT COUNT(*) FROM tblmembers WHERE mem_email = ?",$mem_email);
list($count)=mysql_fetch_row($r);

if($count > 0)
redirect("/message.php?message=already_a_member");

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.