php - PDO and checking if username or email is taken -


i converting pdo , i'm having problem converting @ section checks see if username , email taken or not.

below code:

<?php session_start(); $host     = "localhost"; $username = "root"; $password = "123"; $dbname   = "test"; $conn = new pdo("mysql:host=$host;dbname=$dbname",$username,$password); ?>  <?php if(isset($_post['register'])){ $username = $_post['username']; $password = $_post['password']; $email = $_post['email'];      $usernamecheck = $conn->query("select `id` `user`                   username='$username'");     $emailcheck  = $conn->query("select `id` `user` email='$email'");     if(mysql_num_rows($usernamecheck) > 0){         echo "that username taken";     }elseif(mysql_num_rows($emailcheck) > 0){         echo "that e-mail address in use"; }     ?> 

the errors @ 2 following lines:

if(mysql_num_rows($usernamecheck) > 0){

}elseif(mysql_num_rows($emailcheck) > 0){

thanks in advance.

you're using mysql_num_rows() pdo query. can't mix these apis.

you're interpolating $_post variables directly sql, no-no security. benefit of using pdo can use sql query parameters instead, easier , more secure.

here's how i'd code task:

$conn->setattribute(pdo::attr_errmode, pdo::errmode_exception);  $stmt = $conn->prepare("select count(*) count `user` username=?"); $stmt->execute(array($username)); while ($row = $stmt->fetch(pdo::fetch_assoc)) {   $username_count = $row["count"]; } if ($username_count > 0) {   echo "that username taken"; }  $stmt = $conn->prepare("select count(*) count `user` email=?"); $stmt->execute(array($email)); while ($row = $stmt->fetch(pdo::fetch_assoc)) {   $email_count = $row["count"]; } if ($email_count > 0) {   echo "that email address in use"; } 

also keep in mind even if check first, should assume someday 2 people may trying create same username simultaneously, , if code respective requests executes in wrong sequence, both told username not exist, go ahead , insert it. should define unique key on columns must unique. first 1 insert succeed, other error. must check errors.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -