使用PDO调用null上的成员函数query()

时间:2016-03-26 17:10:46

标签: php mysql pdo

我刚检查了stackoverflow上可用的所有答案,它们是相似的,但不是我的答案。所以请不要将此帖重复。

这些是我的代码,当我执行它时说

  

致命错误:在null中调用成员函数query()   第12行的C:\ wamp64 \ www \ ourCMS \ index.php

这是我的代码:

<?php

class DB
{
    private $dbHost;
    private $dbName;
    private $dbUser;
    private $dbPass;

    protected $con;

    function set_db($host, $db, $user, $pass)
    {
        $this->dbHost = $host;
        $this->dbName = $db;
        $this->dbUser = $user;
        $this->dbPass = $pass;

    }

    function connect()
    {
        $info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
        try
        {
            $this->con = new PDO($info, $this->dbUser, $this->dbPass);
        }
        catch(PDOException $e)
        {
            print "Error Founds: ".$e->getMessage().PHP_EOL;
            die();
        }
    }
}

// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
    include('include/database.php');

    $database = new DB;
    $database->set_db("localhost", "ourcms", "root", "");
    $conn = $database->connect();

    $name = $_POST['nm'];
    $query = "INSERT INTO testingpdo (name) VALUES ('$name')";
    $data = $conn->query($query);
    $result = $data->fetchAll(PDO::FETCH_ASSOC);

    print_r($result);
}

1 个答案:

答案 0 :(得分:1)

您不会从DB :: connect(@media only screen and (min-width: 300px) { input:focus, select:focus, textarea:focus, button:focus { -webkit-appearance: none; outline: none; } } )返回任何内容。在函数末尾添加$conn = $database->connect();

return $this->con;