首页 > 解决方案 > 我无法解决此错误 在 null 上调用成员函数 quote()

问题描述

我正在本地主机上编写网站,当我尝试登录以提交新用户时发现此错误

致命错误:未捕获的错误:在 C:\xampp\htdocs\recipes\db_manager\users.php:31 中调用成员函数 quote() 堆栈跟踪:#0 C:\xampp\htdocs\recipes\users_manager\checkSubmit .php(15): notExistsUser('usertest') #1 {main} 在第 31 行的 C:\xampp\htdocs\recipes\db_manager\users.php 中抛出

检查提交.php:

<?php
    session_start();
    include_once("../db_manager/common.php");
    if(isset($_POST["username"]) && isset($_POST["pwd"])) {
        $username = $_POST["username"];
        $pwd = $_POST["pwd"];
        if(notExistsUser($username)){
            submit($username, $pwd);
            redirect("../index.php", "User successfully submitted!");
        } else {
            redirect("../submit.php", "This username already exists");
        }
    }
?>

users.php 中的函数 notExistsUser

function notExistsUser($username) {
    $db = attachdb();
    $user = $db->quote($username); //Line 31
    $rows = $db->query("SELECT * FROM Users WHERE username = $user");
    if($rows->rowCount() > 0)
        return false;
    else
        return true;
}

函数附加数据库()

function attachdb() {
    $add = 'mysql:dbname=Recipes;host=localhost';
    try {
        $db = new PDO($add, 'root', 'mysql');
        return $db;
    } catch (PDOException $ex) {
        ?>
        <p>A database error occurred!.</p>
        <?php
        return NULL;
    }
}

这个错误是什么意思,我该如何解决?

标签: phpmysqldatabaseweb

解决方案


您的数据库连接一定是错误的。你确定你的root密码是mysql吗?attachdb() 将在连接问题时返回 NULL。

// at this point $db IS NULL and not the desired PDO Instance
$user = $db->quote($username); //Line 31

要解决这个问题:您必须确保数据库连接正常工作,然后没有错误。


推荐阅读