这是我使用的代码:
<?php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (!empty($username)){
if (!empty($password)){
$host = "localhost";
$dbusername = "root";
$dbpassword = "1234";
$dbname = "admin";
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
$dbunames = mysqli_query("SELECT * FROM entity WHERE username='$username'");
if (mysqli_num_rows($dbunames) > 0 ) { //check if there is already an entry
for that username
echo "Already taken";
}
else{
$sql = "INSERT INTO entity (username, password)
values ('$username','$password')";
if ($conn->query($sql)){
echo "New record is inserted sucessfully";
}
else{
echo "Error: ". $sql ."
". $conn->error;
}
$conn->close();
}
}
else{
echo "Password should not be empty";
die();
}
}
else{
echo "Username should not be empty";
die();
}
?>
这是错误(在网络上):
Warning: mysqli_query() expects at least 2 parameters, 1 given in
C:\xampp\htdocs\form\connect.php on line 15
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null
given in C:\xampp\htdocs\form\connect.php on line 19
New record is inserted sucessfully
我知道“记录已成功插入”,但是用户名已被使用,验证不起作用。 我不擅长php,所以如果您告诉我如何简单地解决此代码,我将感到高兴。
请帮助我!
答案 0 :(得分:1)
您需要将$ conn添加为查询中的第一个参数。由于您的查询未正确执行,因此mysql_num_rows()
也不起作用。
更改
$dbunames = mysqli_query("SELECT * FROM entity WHERE username='$username'");
收件人
$dbunames = mysqli_query($conn, "SELECT * FROM entity WHERE username='$username'");
此外,您现在编写的查询对于进行sql注入并不安全。您应该花30分钟来阅读如何使用参数化查询。一点都不错,现在就学习它,这样您就可以确保以后的所有查询均已正确编码。这是正确的事情。 这是一个很好的阅读链接,它将解释使用mysqli进行参数化查询。 Good SQL Practices
这里是如何正确编码上面的查询的示例。
$stmt = $conn->prepare("SELECT * FROM entity WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0){
echo "That username is already taken.";
}
$stmt->close();
答案 1 :(得分:0)
$dbunames = mysqli_query("SELECT * FROM entity WHERE username='$username'");
需要像这样使用$ conn变量:
$dbunames = mysqli_query($conn, "SELECT * FROM entity WHERE username='$username'");
答案 2 :(得分:0)
正如我在评论中所说:
mysqli_query
函数需要传递两个参数。
更改此:
$dbunames = mysqli_query("SELECT * FROM entity WHERE username='$username'");
对此:
$dbunames = mysqli_query($conn, "SELECT * FROM entity WHERE username='$username'");
答案 3 :(得分:0)
您忘记在// Create connection
部分添加$ conn变量,因此它应该是:
$dbunames = mysqli_query($conn, "SELECT * FROM entity WHERE username='$username'");
也始终将密码存储为哈希!