每当我在登录表单上的html username
文本输入字段中只输入字母时,就会出现错误:
mysqli_num_rows()期望参数1为mysqli_result ...
即使数据库中存在用户名。
但是,当我只在输入字段中输入数字时,它可以正常工作。
这是我的PHP文件:
<?php
//start a session
//unset session variables, expire session cookie, destroy session
//start a new session
session_start();
$_SESSION = array();
setcookie('PHPSESSID', '', time() + 1);
session_destroy();
session_start();
//require template_functions.php file
//call function that renders layout with content file: home.php
require $_SERVER['DOCUMENT_ROOT'] .
'/practice2/resources/library/template_functions.php';
layout('/practice2/public_html/php/home.php');
//if 'login' btn clicked
if (isset($_POST['login'])) {
//assign variable to user's typed username
$name = mysqli_real_escape_string($link, $_POST['name']);
//assign variable to user's typed pw
$pw = mysqli_real_escape_string($link, $_POST['pw']);
//if user typed name
if ($name){
//number of matches to user's name
$result = mysqli_num_rows(
mysqli_query($link, 'SELECT * FROM user WHERE name = ' .$name));
echo $result;
//if name doesn't match
if ($result == 0) {
echo 'The username that you\'ve entered doesn\'t match any account.';
//if name matches
} else if ($result == 1) {
//if user typed pw
if ($pw) {
//number of matches to user's pw
$result = mysqli_num_rows(
mysqli_query($link, 'SELECT * FROM user WHERE pw =' .$pw));
//if pw doesn't match
if ($result == 0) {
echo 'The password that you\'ve entered is incorrect. Forgetten password?';
//if pw match
} else
//assign session variables
//$_SESSION['loggedin'] = true;
//$_SESSION['name'] = $name;
echo 'signed in';
} else echo '<br> Log in as ' .$name. '. Not you?';
}
}
}
?>
这是我提交给PHP文件的HTML文件:
<html>
<body>
<form action = '/practice2/public_html/php/index.php' method = 'POST'>
<input type = 'text' placeholder = 'Username' name = 'name'>
<input type = 'password' placeholder = 'Password' name = 'pw'>
<input type = 'submit' value = 'Log In' name = 'login'>
</form>
</body>
</html>
答案 0 :(得分:0)
首先,仔细检查您是否已建立数据库连接。并写下你的查询:
$result = mysqli_num_rows(mysqli_query($link, 'SELECT * FROM user WHERE name ="'.$name.'"'));
echo $result;
答案 1 :(得分:0)
SQL将允许您搜索没有引号的数字,但不会搜索文本。
SELECT * FROM user WHERE name = 1234
没问题。
SELECT * FROM user WHERE name = fred
不是。
如果用引号包围搜索到的参数,那么你应该过得更好。
即。 mysqli_query($link, 'SELECT * FROM user WHERE name = "' . $name . '"'));
请注意,虽然您要转义参数以防止SQL injection使用mysqli_real_escape_string(),但我建议您还查看Prepared Statements in PHP上的教程