当前位置:  开发笔记 > 编程语言 > 正文

prepare()函数出错

如何解决《prepare()函数出错》经验,为你挑选了1个好方法。

我有这个登录页面,我在看Udemy的教程时写了它.他的代码工作正常,但在我的代码(相同)中,我有以下错误:

致命错误:在非对象上调用成员函数prepare()

这是代码:

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //Adding a character set:
    $conn = exec("SET CHARACTER SET utf8mb4");

    $user = '';
    $pass = '';
    $sum = 0;
    $error_msg = "Please type a username and a password";
    if(isset($_POST['login_submit']))
    {
        //Start a session:
        session_start();
        $user = $_POST['username'];
        $pass = $_POST['password'];
        if(empty($user) && empty($pass))
        {
            echo $error_msg;
            $pass = '';
        }
        if(empty($user) || empty($pass))
        {
            echo $error_msg;
            $user = '';
            $pass = '';
        }
        if(!empty($user) && !empty($pass))
        {
            //SQL:
            $query = $conn->prepare("SELECT * FROM login WHERE user = :u AND password= :p LIMIT 1");
            $query->bindParam(":u", $user);
            $query->bindParam(":p", $pass);
            //Execute query:
            $query->execute();
            $number_rows = $query->fetch(PDO::FETCH_NUM);
            if($number_rows>0)
            {
                echo $user;
                $_SESSION = $user;
                $_SESSION = $pass;
                header("Location: /pages/home.php");
            }
            else
            {
                echo "Invalid username or password";
                header("Location: index.php");
            }
            //echo $user;
        }
    }
    if(!isset($_POST['login_submit']))
    {
        echo "Login button not clicked";
    }
?>

trincot.. 6

使用以下语句销毁$ conn对象:

$conn = exec("SET CHARACTER SET utf8mb4");

替换为:

$conn->exec("SET CHARACTER SET utf8mb4");

请注意,从PHP 5.3.6开始,您可以在连接字符串中设置字符集,如下所示:

$conn = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8", $dbuser, $dbpass);

exec然后不再需要单独的呼叫.



1> trincot..:

使用以下语句销毁$ conn对象:

$conn = exec("SET CHARACTER SET utf8mb4");

替换为:

$conn->exec("SET CHARACTER SET utf8mb4");

请注意,从PHP 5.3.6开始,您可以在连接字符串中设置字符集,如下所示:

$conn = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8", $dbuser, $dbpass);

exec然后不再需要单独的呼叫.

推荐阅读
依然-狠幸福
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有