使用PHP检查MySQL表中是否存在用户名?
我想创建一个代码来检查服务器上是否已经存在用户名,或者是否使用MySQL和PHP。守则:使用PHP检查MySQL表中是否存在用户名?,php,mysql,sql,Php,Mysql,Sql,我想创建一个代码来检查服务器上是否已经存在用户名,或者是否使用MySQL和PHP。守则: // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT username FRO
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT username FROM Servers where email=".$user_info['email']."";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
//username exists
}
else
{
//...
}
我不断地发现这个错误:
警告:mysqli_num_rows()要求参数1为mysqli_结果,布尔值在
这不是正确的方法,您必须找到计数:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT COUNT(username) AS 'count' FROM Servers where email= '".$user_info['email']."'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$num = mysqli_fetch_array($result);
if ($num['count'] > 0) {
// user dublicate
} else{
// new user
}
- 对于数据库中的字符串,必须使用引号
”“
- 您必须使用count来优化代码
- 您必须在代码中绕过sql注入
您的代码有sql注入错误。也许这可以解决问题。稍微修改一下代码
$email = $user_info['email'];
$sql = "SELECT username FROM Servers where email='$email'";
用这个-
$sql=“从电子邮件地址为“$user\u info['email']”的服务器中选择用户名。”“” 您不希望通过将用户输入连接到字符串来生成SQL查询。这可能导致严重后果 您想删除您的查询。首先向MySQL声明查询的结构,然后绑定参数并调用它以获得结果。这就像使用一个函数:很少使用用户输入动态生成它。将SQL查询视为函数
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$emailIsValid = false;
// Initialize a query. Note how we replaced the variable by a '?'. This indicates a parameter.
$sql = "SELECT username FROM Servers where email=?";
$query = mysqli_stmt_init($conn);
if (mysqli_stmt_prepare($query, $sql)){
// Declare the user email as first parameter of the query
mysqli_stmt_bind_param($query, "s", $user_info['email']);
// Executes the query
mysqli_stmt_execute($query);
// Bind the result to a variable
mysqli_stmt_bind_result($query, $result);
// Read first result
if(mysqli_stmt_fetch($query)){
// At least one user, so the email exists
$emailIsValid = true;
}
// If we don't need the query anymore, we remove it
mysqli_stmt_close($query);
}
if ($emailIsValid) {
//username exists
}
else
{
//...
}
有关更多信息,请查看。尽管我建议您改为使用。可能是您的查询有错误,请使用它,如->“从服务器中选择用户名,其中email=“”。$user_info['email']”;你很容易受到伤害。使用数据绑定。您还可以在用户名列(以及电子邮件,如果您愿意)上设置唯一索引,并让服务器在您尝试添加副本时通知您。(我想检查“用户名是否已经有服务器”的唯一原因)