php - Check if user exists in database -


i've made user class validates data passed through form , subsequently updates database table users. want add functionality such checking if username , email exists in table, i've added little script doesn't seem working.

i inserted duplicated email address , did not error message "email exists" instead success message "1 row inserted":

am doing wrong below? there perhaps better way approach this?

 public function insert() {  if (isset($_post['submit'])) {     $email = isset($_post['email']) ? $this->mysqli->real_escape_string($_post['email']) : '';  $result = $this->mysqli->prepare("select * users email='".$email."'");  if ($result->num_rows) { echo "email exisits!"; }   else  { $stmt = $this->mysqli->prepare("insert users (username, password, name, email) values (?, ?, ?, ?)");         $stmt->bind_param('ssss', $username, $password, $name, $email); // bind strings paramater         //escape post data added protection  $username = isset($_post['username']) ? $this->mysqli->real_escape_string($_post['username']) : ''; $cryptedpassword = crypt($_post['password']); $password = $this->mysqli->real_escape_string($cryptedpassword);     $name = isset($_post['name']) ? $this->mysqli->real_escape_string($_post['name']) : '';     $email = isset($_post['email']) ? $this->mysqli->real_escape_string($_post['email']) : '';         /* execute prepared statement */ $stmt->execute();     printf("%d row inserted.\n", $stmt->affected_rows);     /* close statement , connection */ $stmt->close();             } 

you using worst api ever can choose.

with safemysql be

$exists = $this->db->getone("select 1 users email=?s", $_post['email']); if ($exists) {     echo "email exisits!"; }  

with pdo longer usable

$stmt = $this->db->prepare("select 1 users email=?"); $stmt->execute(array($_post['email'])); $exists = $stmt->fetchcolumn(); if ($exists) {     echo "email exisits!"; }  

but raw mysqli need screenful of code check if user exists.

so, whole function using safemysql be

public function insert() {     if (!isset($_post['submit'])) {         return false;     }      $sql    = "select 1 users email=?s";     $exists = $this->db->getone($sql, $_post['email']);     if ($exists)     {         echo "email exisits!";         return false;      }     $sql     = "insert users set ?u";     $allowed = array('username', 'name', 'email');     $insert  = $this->db->filterarray($_post, $allowed);     $insert['password'] = crypt($_post['password']);     $this->db->query($sql, $insert);     return $this->db->afectedrows(); } 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -