如果语句在mysql中注册

时间:2017-08-03 08:12:00

标签: php mysql

在我的应用程序中,此PHP代码应检查现有用户名,如果存在,则不要在数据库中创建新行。无论如何,应用程序仍在MySQL数据库中创建新行。

以下是检查代码:

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

?>

1 个答案:

答案 0 :(得分: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. 您应该使用mysqli而不是mysql,因为它已被弃用
  2. 其次,您应该检查if($results->num_rows === 0)并执行INSERT