在poll.class.php

时间:2019-02-18 10:30:49

标签: php mysql sql

我正在创建一个简单的网站民意调查。我收到此错误,我无法弄清楚我的代码有什么问题。错误说 致命错误:在第28行的C:\ xampp \ htdocs \ poll \ models \ poll.class.php中调用成员函数prepare()上的空值

这是我初始化数据库连接的索引文件的代码:

<?php

    error_reporting(E_ALL);
    ini_set("display_errors", 1);

    //load model
    include_once "models/Page_Data.class.php";

    $PageData = new Page_Data;
    $PageData->title = "PHP/MySQL site poll example";

    $PageData->content .= include_once "controllers/poll.php";

    //database credentials
    $dbInfo = "mysql:host=localhost;dbname=playground";
    $dbUser = "root";
    $dbPassword = "";

    try {
        $db = new PDO( $dbInfo, $dbUser, $dbPassword );
        $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    } catch ( Exception $e ) {
        $pageData->content = "<h1>Connection failed!</h1><p>$e</p>";
    }

    $page = include_once "views/page.php";
    //output generated page
    echo $page;

成员函数prepare()在我的模型文件(poll.class.php)中。这是代码:

<?php
    include_once "controllers/poll.php";
    global $db;
    class Poll
    {
        //method requires a database connection as argument
        public function __construct( $dbConnection )
        {
            //store the received conection in the $this->db property\
            $this->db = $dbConnection;  
        }

        public function updatePoll( $input )
        {

            if ( $input==='yes'){
                $updateSQL = "UPDATE poll SET yes = yes + 1 WHERE poll_id = 1";
            } else if ( $input === 'no'){
                $updateSQL = "UPDATE poll SET no = no + 1 WHERE poll_id = 1";
            }
            $updateStatement = $this->db->prepare($updateSQL);
            $updateStatement->execute();
        }

        public function getPollData()
        {
            //The actual SQL statement 
            $sql = "SELECT poll_question, yes, no FROM poll WHERE poll_id = 1";
            //Use the PDO connection to create a PDOStatement object
            $statement = $this->db->prepare($sql);
            //tell MySQL to execute the statement
            $statement->execute();
            //retrieve the first row of data from the table
            $pollData = $statement->fetchObject();
            //make poll data available to the caller    
            return $pollData;
        }
    }

我正在控制器(poll.php)中调用db。这是代码:

<?php
    include_once "models/poll.class.php";

    $poll = new Poll( $db );
    //check if the poll is submitted 
    $isPollSubmitted = isset($_POST['user-input']);
    if ($isPollSubmitted){
        $input = $_POST['user-input'];

        $poll->updatePoll($input);
    }

    $pollData = $poll->getPollData();
    $pollAsHtml = include_once "views/poll-html.php";
    return $pollAsHtml;

0 个答案:

没有答案