我想创建一个代码来检查服务器上是否已存在用户名,或者是否使用MySQL和PHP。代码:
// 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_result,布尔值在
中给出
答案 0 :(得分:1)
也许这可以解决问题。稍微修改一下代码..
$email = $user_info['email'];
$sql = "SELECT username FROM Servers where email='$email'";
答案 1 :(得分:1)
使用此 -
$ sql =" SELECT username FROM Servers where email = '"。$ user_info [' email']。"' 强>&#34 ;;
答案 2 :(得分:1)
您不希望通过将用户输入连接到字符串来生成SQL查询。这可能会导致SQL injection。
您希望parameterize您的查询。首先,向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
{
//...
}
查看mysqli docs以获取更多信息。虽然我建议你改用PDO。
答案 3 :(得分:0)
这种不正确的方式你必须找到计数:
// 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
}
'
作为字符串并且你的代码有sql注入错误。