我正在转换为PDO,我在检查用户名和电子邮件是否被采取的部分转换时出现问题。
下面是代码:
<?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` FROM `user` WHERE username='$username'");
$emailcheck = $conn->query("SELECT `id` FROM `user` WHERE email='$email'");
if(mysql_num_rows($usernamecheck) > 0){
echo "That username is already taken";
}elseif(mysql_num_rows($emailcheck) > 0){
echo "That e-mail address is already in use";
}
?>
我得到的错误是以下两行:
if(mysql_num_rows($ usernamecheck)&gt; 0){
} elseif(mysql_num_rows($ emailcheck)&gt; 0){
先谢谢。
答案 0 :(得分:1)
首先,整个任务相当没有意义。使用户名唯一是没有意义的。给定电子邮件用于识别用户,用户名 - 或者更确切地说 - 显示名称可以是任何内容并允许重复,就像在 Stack Overflow 上在这里所做的一样。
但是如果您希望用户名是唯一的,显然可以在一个查询中完成,而无需 any num rows 功能,essentially useless
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT username, email AS count FROM `user` WHERE username=? OR email=?";
$stmt = $conn->prepare($sql);
$stmt->execute([$username, $email]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($row['username'] === $username) {
$errors[] = "Username is taken";
}
if ($row['email'] === $email) {
$errors[] = "Email is taken";
}
}
答案 1 :(得分:0)
您正在使用mysql_num_rows()
进行PDO查询。你不能混用这些API。
您还将$ _POST变量直接插入到SQL中,这对于安全性来说是禁忌。使用PDO的好处是您可以轻松使用SQL查询参数,这样更容易,更安全。
以下是我编写此任务的方式:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT COUNT(*) AS count FROM `user` WHERE username=?");
$stmt->execute(array($username));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$username_count = $row["count"];
}
if ($username_count > 0) {
echo "That username is already taken";
}
$stmt = $conn->prepare("SELECT COUNT(*) AS count FROM `user` WHERE email=?");
$stmt->execute(array($email));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$email_count = $row["count"];
}
if ($email_count > 0) {
echo "That email address is already in use";
}
还要记住即使你先检查,你应该假设有一天有两个人可能会同时尝试创建相同的用户名,并且如果他们各自的请求的代码只执行错误的序列,他们都可以被告知用户名不存在,继续并插入它。因此,您应该在必须唯一的列上定义UNIQUE KEY。只有INSERT的第一个会成功,另一个会出错。所以你必须检查错误。