num_rows在面向对象方法中不起作用



我是php&mysql。num_rows在以下基本示例中不起作用。整个脚本的灵感来自w3schools中的示例。w3schools示例。

浏览器显示如下错误消息。

注意:在第17行的C:\wamp\www\test3\index.php中尝试获取非对象的属性

代码

<?php
require 'connect.inc.php';
require 'core.inc.php';
//check username & password is set.
if(isset($_POST['username']) && isset($_POST['psw'])) 
{
    $username = $_POST['username'];
    $password = $_POST['psw'];
    $pass_md5 = md5($password);
    if(!empty($username) && !empty($password))
    {
        $queryy = "SELECT ID FROM user WHERE email= $username AND password= $pass_md5";
        $result = $conn->query($queryy);
        echo $result->num_rows; //<---------------NOT WORKING..! -----<<
    }
    else echo "incorrect username-password combination";
}
?>
<html>
<form action="<?php echo $current_file ?>" method="POST">
    User name: <input type="text" name="username">
    password: <input type="password" name="psw">
    <input type="submit" value="Login"><br>
</form>
<html>

其中connect.inc.php有一些简单的代码来连接到localhost和数据库。如下所示:

<?php
//this sript connects to DB->mytest.
$servername="localhost";
$username="root";
$password="";
$dbname="mytest";
//create connection
@$conn=new mysqli($servername, $username, $password, $dbname);
//check connection
if($conn->connect_error)
{
    die("connection faild");
}
?>

并且,core.inc.php返回当前文件位置。如下所示:

<?php
$current_file = $_SERVER['SCRIPT_NAME'];
?>

请帮忙。。

问题是您没有在查询中引用字符串:

$queryy = "SELECT ID FROM user WHERE email= '$username' AND password= '$pass_md5'";

但是,最好使用准备好的查询和bind_param,而不是替换变量。

$queryy = "SELECT ID FROM user where email = ? AND password = ?";
$stmt = $conn->prepare($queryy);
$stmt->bind_param("ss", $username, $pass_md5);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows;

您的$conn似乎没有正确连接到数据库,或者它没有运行查询所需的权限。或者您的查询无效。

编辑:您的查询缺少':

$queryy = "SELECT ID FROM user WHERE email= '$username' AND password= '$pass_md5'"

相关内容

  • 没有找到相关文章

最新更新