prepare()函数

时间:2015-12-22 07:41:20

标签: php html mysql sql pdo

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

  

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

这是代码:

<?php
    //$var = 'This is our first web app page';
    //echo $var;

    //Connection Variables:
    $dbhost = "localhost";
    $dbname = "graphic_db";
    $dbuser = "root";
    $dbpass = "root";

    //Connection to SQL:
    $conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $dbuser, $dbpass);
    //Error messagin enabled:
    $conn->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";
    }
?>

1 个答案:

答案 0 :(得分: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电话。