0

In my app, this PHP code should check for existing usernames and if one exists, don't create a new row in the database. No matter what, the app still creates new rows in the MySQL database.

Here is the code for checking:

<?php 

//$password = "password";
//$username = "username";
require "conn.php";
$password = $_POST["password"];
$username = $_POST["username"];
//$url_id = mysql_real_escape_string($_GET['username']);
$sql = "SELECT * FROM UserData WHERE username ='$username'";
$result = mysql_query($sql);

if(mysql_num_rows($result) >0){
   break;
}else{
   $stmt = $conn->prepare("INSERT INTO UserData (username,password) VALUES (:username,:password)");
$params = array(
    ':username' => $username,
    ':password' => $password
);
$stmt->execute($params);
}

?>
  • you **MUST NOT** use `mysql_xxx` functions which are deprecated since php5.5 (more than 3 years ago) and removed since PHP7 because of security issues (see http://stackoverflow.com/q/12859942/3992945). Please use `mysqli_xxx` or `PDO` instead http://php.net/manual/en/mysqlinfo.api.choosing.php. – ᴄʀᴏᴢᴇᴛ Aug 03 '17 at 08:13
  • This is the wrong way to go about this to begin with. You want to make the username field UNIQUE in your database scheme, and then check if an error violating this constraint occurs when you try and insert a new record. – CBroe Aug 03 '17 at 08:14
  • Check both the contents of `$sql` and the return value of `mysql_num_rows($result)`. Also the break statement doesn't really belong here; it's for use in loops. But it doesn't do anything at all, which is probably what you want. Also the advice from CROZET about using modern/supported mysql libraries is definitely something to heed – Lorna Mitchell Aug 03 '17 at 08:15
  • You are mixing mysql and mysqli functions and also you mix object and procedural code – ᴄʀᴏᴢᴇᴛ Aug 03 '17 at 08:17

1 Answers1

0
$results = $mysqli->query("SELECT * FROM UserData WHERE username ='$username'");
if ($results) { 
    if($results->num_rows === 0)
    {
        $stmt = $conn->prepare("INSERT INTO UserData (username,password) VALUES (:username,:password)");
        $params = array(
            ':username' => $username,
            ':password' => $password
        );
        $stmt->execute($params);
    }
}
?>
  1. You should use mysqli and not mysql as it is deprecated
  2. Secondly, you should check if($results->num_rows === 0) and do your INSERT
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35