Jump to content


Photo

Redirect if record already exists in database


  • Please log in to reply
2 replies to this topic

#1 ramone_johnny

ramone_johnny

    Advanced Member

  • Members
  • PipPipPip
  • 50 posts
  • LocationSydney, NSW

Posted 24 May 2013 - 10:25 PM

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");

Works Media - Online Marketing & SEO


#2 Strider64

Strider64

    Advanced Member

  • Members
  • PipPipPip
  • 154 posts
  • LocationA burb of Detroit, MI

Posted 24 May 2013 - 11:04 PM

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;
}



Who do you think is going to win the World Series? Vote up to 5 times here : http://www.pepster.c...booth/index.php


#3 mac_gyver

mac_gyver

    Advanced Member

  • Administrators
  • 2,568 posts

Posted 25 May 2013 - 09:28 AM

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");

Edited by mac_gyver, 25 May 2013 - 09:31 AM.

multi-purpose programming fool. well written source-code should be self-documenting. well written code should be self-troubleshooting. 





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com