Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP OOP-尝试调用方法_Php_Mysql_Oop - Fatal编程技术网

PHP OOP-尝试调用方法

PHP OOP-尝试调用方法,php,mysql,oop,Php,Mysql,Oop,只是想让我的头脑清醒一下。有人告诉我,我把下面的脚本写错了。我之前试图从数据库类调用一个方法。实际上,数据库类应该只处理数据库内容。因此,我现在创建了一个html_class.php,我认为我需要在其中访问数据库类,然后通过这个类输出html 我试图调用index.php的方法是getBlogPost()方法,该方法位于html\u class.php文件中。我试图使用echo$htmlObject->getBlogPosts()调用此函数 我想这是做这件事的正确方法 我当前收到以下错误: No

只是想让我的头脑清醒一下。有人告诉我,我把下面的脚本写错了。我之前试图从数据库类调用一个方法。实际上,数据库类应该只处理数据库内容。因此,我现在创建了一个html_class.php,我认为我需要在其中访问数据库类,然后通过这个类输出html

我试图调用
index.php
的方法是
getBlogPost()
方法,该方法位于
html\u class.php
文件中。我试图使用echo
$htmlObject->getBlogPosts()调用此函数

我想这是做这件事的正确方法

我当前收到以下错误:

Notice: Undefined variable: db_login_info in C:\xampp\htdocs\xampp\oop\CMS\classes\html_class.php on line 14

Fatal error: Cannot access private property database::$objDbConn in C:\xampp\htdocs\xampp\oop\CMS\classes\html_class.php on line 15
index.php

<?php 
require_once("includes/header.php");
require_once("includes/footer.php");
require_once("classes/database_class.php");
require_once("classes/blog_post_class.php");
require_once("classes/html_class.php");
require_once("conf/config.php");

$header = new header();
// createHeader( Title | Description | Keywords)
echo $header->createHeader('Home - Nissan Skyline GTR Blog', 'This is a blog site about the Nissan GTR', 'Nissan, GTR, R35');

$dbObject = new database($db_login_info);
$htmlObject = new makeHTML();


 ?>
    <div id="container">
        <div id="top_nav">
        <a href="admin.php" class="admin_link">Admin Login</a>
        </div>

            <div id="header"></div>

            <div id="nav">
                <ul>
                    <li><a href="index.php">Home</a></li>
                    <li><a href="create-blog.php">Create Blog</a></li>
                    <?php 
                    $sql = "SELECT * FROM create_page";
                    echo $dbObject->createNavigation($sql);
                     ?>
                </ul>
            </div>

            <div id="content_area">
                <?php 
                echo $htmlObject->getBlogPosts(); // Calling the getBlogPost function located in the html_class.php

                // echo $dbObject->getBlogPosts();

                 ?>


            </div>
<?php 
$footer = new footer();
echo $footer->createFooter();
 ?>
<?php    

class database {
        private $objDbConn;

        function __construct($db_login_info){
            $this->objDbConn = new mysqli($db_login_info['host'], $db_login_info['username'],
                                        $db_login_info['password'], $db_login_info['database']);

             if (mysqli_connect_errno()) {
                        die("Database connection failed". mysqli_connect_error());
                }
        }
        // I was previoulsy calling this method below on the index.php page and it was working great
        // function getBlogPosts(){
        //  $objRes = mysqli_query($this->objDbConn, "SELECT * FROM `blog_posts` ORDER BY id DESC");
        //   if(mysqli_errno($this->objDbConn)) {
        //      die("Failed query: $strSql". $this->objDbConn->error);
        //   }
        //   $allrows ='';
        //   while ($row = mysqli_fetch_array($objRes)) {

        //      $time = strtotime($row['date']);
        //      $my_format = date("m/d/y @ g:ia", $time);

        //      $allrows .= '<div id="blog_post">';
        //      $allrows .= '<h2 id="blog_title">'.$row['title'].'</h2>';
        //      $allrows .= '<h5> Posted on the '.$my_format.'</h5>'."<br>";
        //      $allrows .= '<div id="blog_content">'.nl2br($row['content']).'</div>'."<br>";
        //      $allrows .= '<b>ID:</b>'.$row['id'].'<a href="delete.php?id='.$row['id'].'" name="delete" onclick="return confirm(\'Are you sure you want to delete this post?\');"> Delete</a></div>';
        //   };

        //   return $allrows;



        // }

    ?>
<?php 
require_once("includes/header.php");
require_once("includes/footer.php");
require_once("classes/database_class.php");
require_once("classes/blog_post_class.php");
require_once("classes/html_class.php");
require_once("conf/config.php");


class makeHTML {


    function getBlogPosts(){
        $dbObject = new database($db_login_info); // This is where the Notice: Undefined variable: db_login_info is happening
        $objRes = mysqli_query($dbObject->objDbConn, "SELECT * FROM `blog_posts` ORDER BY id DESC");
         if(mysqli_errno($dbObject->objDbConn)) {
            die("Failed query:". $dbObject->objDbConn->error);
         }
         $allrows ='';
         while ($row = mysqli_fetch_array($objRes)) {

            $time = strtotime($row['date']);
            $my_format = date("m/d/y @ g:ia", $time);

            $allrows .= '<div id="blog_post">';
            $allrows .= '<h2 id="blog_title">'.$row['title'].'</h2>';
            $allrows .= '<h5> Posted on the '.$my_format.'</h5>'."<br>";
            $allrows .= '<div id="blog_content">'.nl2br($row['content']).'</div>'."<br>";
            $allrows .= '<b>ID:</b>'.$row['id'].'<a href="delete.php?id='.$row['id'].'" name="delete" onclick="return confirm(\'Are you sure you want to delete this post?\');"> Delete</a></div>';
         };

         return $allrows;
    }
}



 ?>
<?php 

// Database login details below

$db_login_info = array(
    'host'=>'localhost',
    'username'=>'root',
    'password'=>'',
    'database'=>'cms'
    );

 ?>
<?php 
require_once("includes/header.php");
require_once("includes/footer.php");
require_once("classes/database_class.php");
require_once("classes/blog_post_class.php");
require_once("classes/html_class.php");
require_once("conf/config.php");


class makeHTML {

    private $database;

    public function __construct(database $database){
        $this->database = $database;
    }

    function getBlogPosts(){

        $objRes = mysqli_query($this->database, "SELECT * FROM `blog_posts` ORDER BY id DESC");
         if(mysqli_errno($this->database)) {
            die("Failed query:". $this->database->error);
         }
         $allrows ='';
         while ($row = mysqli_fetch_array($objRes)) {

            $time = strtotime($row['date']);
            $my_format = date("m/d/y @ g:ia", $time);

            $allrows .= '<div id="blog_post">';
            $allrows .= '<h2 id="blog_title">'.$row['title'].'</h2>';
            $allrows .= '<h5> Posted on the '.$my_format.'</h5>'."<br>";
            $allrows .= '<div id="blog_content">'.nl2br($row['content']).'</div>'."<br>";
            $allrows .= '<b>ID:</b>'.$row['id'].'<a href="delete.php?id='.$row['id'].'" name="delete" onclick="return confirm(\'Are you sure you want to delete this post?\');"> Delete</a></div>';
         };

         return $allrows;
    }
}
class database {
    public $objDbConn;

    function __construct($db_login_info){
        $this->objDbConn = new mysqli($db_login_info['host'], $db_login_info['username'],
                                    $db_login_info['password'], $db_login_info['database']);

         if (mysqli_connect_errno()) {
                    die("Database connection failed". mysqli_connect_error());
            }


    } 

     ?>
数据库中的fetchall方法\u class.php

function fetchall($sql) {
        $query = mysqli_query($this->objDbConn, $sql);
        if ($this->objDbConn->connect_errno) {
            die("Database connection failed with message: " . $objDbConn->connect_error);
        }
    }
您应该使用“”为
makeHtml
类指定
数据库
对象

\u构造
方法添加到
makeHtml
类:

class makeHtml
{
    private $database;

    public function __construct(database $database)
    {
        $this->database = $database;
    }
$htmlObject = new makeHTML($dbObject);
实例化
makeHtml
类时:

class makeHtml
{
    private $database;

    public function __construct(database $database)
    {
        $this->database = $database;
    }
$htmlObject = new makeHTML($dbObject);
然后在类中,您可以使用
$this->database
引用数据库对象,而不是创建新的数据库对象(每次都创建一个新连接)

请进一步注意,您需要在
数据库中设置
$objDbConn
变量,以便在其他类中访问该变量。然而,在
数据库中有一个处理执行查询和返回结果的方法将是一个“良好实践”。理想情况下,您应该以以下方式结束:

$sql = 'SELECT * FROM `blog_posts` ORDER BY id DESC';
$allRows = $this->database->fetchAll($sql);
<?php 

include "config.php";

$myDatabase = new database($db_login_info);

$html = new makeHTML($myDatabase);

$posts = $html->getBlogPosts();

print($posts);

?>
这将出现在
makeHtml
类中。

您应该使用“”为
makeHtml
类提供
数据库
对象

\u构造
方法添加到
makeHtml
类:

class makeHtml
{
    private $database;

    public function __construct(database $database)
    {
        $this->database = $database;
    }
$htmlObject = new makeHTML($dbObject);
实例化
makeHtml
类时:

class makeHtml
{
    private $database;

    public function __construct(database $database)
    {
        $this->database = $database;
    }
$htmlObject = new makeHTML($dbObject);
然后在类中,您可以使用
$this->database
引用数据库对象,而不是创建新的数据库对象(每次都创建一个新连接)

请进一步注意,您需要在
数据库中设置
$objDbConn
变量,以便在其他类中访问该变量。然而,在
数据库中有一个处理执行查询和返回结果的方法将是一个“良好实践”。理想情况下,您应该以以下方式结束:

$sql = 'SELECT * FROM `blog_posts` ORDER BY id DESC';
$allRows = $this->database->fetchAll($sql);
<?php 

include "config.php";

$myDatabase = new database($db_login_info);

$html = new makeHTML($myDatabase);

$posts = $html->getBlogPosts();

print($posts);

?>

它将出现在您的
makeHtml
类中。

您不能使用对象的私有成员。相反,您可以使用方法或将成员公开。
也不要每次都在配置文件中创建连接对象并包含此文件一次,而是创建连接对象。

您不能使用对象的私有成员。相反,您可以使用方法或将成员公开。
另外,不要每次都在配置文件中创建连接对象并包含此文件一次,而是创建连接对象。

好的,代码中会出现一些不同的情况

首先,您混合了MySQLi的过程版本和面向对象版本。事实上,您使用的是MySQLi,而不是旧版本的MySQL,这是一个很大的优势。但是,您需要在过程或OOP之间进行选择,然后坚持使用它

至于你的错误信息。您将收到关于
$db\u login\u info
的通知,因为它不存在于
getBlogPosts()方法中。当您在方法内部时,您的变量范围将受到限制。这意味着在它之外声明的变量在方法中不可见,除非它们作为参数传入

第二条消息是关于类范围的。变量
$dbObjConn
声明为
private
,这很好,但只能从同一类中访问
private
变量。如果您将其声明为公共
,则您可以按自己的方式访问它

因此,我建议您对代码进行一些修改。拥有一个数据库类并不是一件坏事,它更容易创建一个作为对象的连接,然后将该对象传递给其他需要它的类。但是,在执行此操作时,不应将MySQLi的过程版本与OOP版本混合使用。(我建议您坚持使用OOP版本)

您的
数据库\u class.php
可能如下所示:

class database {
    private $objDbConn;

    function __construct($db_login_info){
        $this->objDbConn = new mysqli($db_login_info['host'], $db_login_info['username'],
                                      $db_login_info['password'], $db_login_info['database']);

        //This is where you are using the procedural interface
        //if (mysqli_connect_errno()) {
        //    die("Database connection failed". mysqli_connect_error());
        //    }
        //}

        //Use the OOP version instead
        if ($this->objDbConn->connect_errno) {
            die("Database connection failed with message: " . $this->objDbConn->connect_error);
        }

    }

    //Keep populating this class with more stuff.  Like:
    public function getDB() {
        return $this->dbObjConn; //use this method to access your private database variable from outside the class
    }
}
html\u class.php
文件也可能需要一些爱:

class makeHTML {

    private $database; //Here is a place for your shiny database object.

    public functon __construct($database) {
        $this->database = $database;
    }

    public function getBlogPosts() {
        $dbObject = $this->database->getDB();
        $objRes = $dbObject->query($dbObject->objDbConn, "SELECT * FROM `blog_posts` ORDER BY id DESC");
         if($dbObject->errno) {
            die("Failed query:". $dbObject->error);
         }
         $allrows ='';
         while ($row = $objRes->fetch_array()) {

            $time = strtotime($row['date']);
            $my_format = date("m/d/y @ g:ia", $time);

            $allrows .= '<div id="blog_post">';
            $allrows .= '<h2 id="blog_title">'.$row['title'].'</h2>';
            $allrows .= '<h5> Posted on the '.$my_format.'</h5>'."<br>";
            $allrows .= '<div id="blog_content">'.nl2br($row['content']).'</div>'."<br>";
            $allrows .= '<b>ID:</b>'.$row['id'].'<a href="delete.php?id='.$row['id'].'" name="delete" onclick="return confirm(\'Are you sure you want to delete this post?\');"> Delete</a></div>';
         };

         return $allrows;
    }

    //Again, keep adding more to this class as you see fit....
}
classmakehtml{
private$database;//这里是您的闪亮数据库对象的位置。
公共函数构造($database){
$this->database=$database;
}
公共函数getBlogPosts(){
$dbObject=$this->database->getDB();
$objRes=$dbObject->query($dbObject->objDbConn,“从`blog_posts`ORDER BY id DESC中选择*);
如果($dbObject->errno){
die(“查询失败:.$dbObject->error”);
}
$allrows='';
而($row=$objRes->fetch_array()){
$time=strottime($row['date']);
$my_format=日期(“m/d/y@g:ia”,$time);
$allrows.='';
$allrows.=''.$row['title'].';
$allrows.='发布在“$my_格式”上。“
”; $allrows.=''.nl2br($row['content'])。'。“
”; $allrows.='ID:'.$row['ID'.'”; }; 返回$allrows; } //再次强调,如果您认为合适,请继续向该类添加更多内容。。。。 }
然后,将所有这些放在一起,您的调用代码如下所示:

$sql = 'SELECT * FROM `blog_posts` ORDER BY id DESC';
$allRows = $this->database->fetchAll($sql);
<?php 

include "config.php";

$myDatabase = new database($db_login_info);

$html = new makeHTML($myDatabase);

$posts = $html->getBlogPosts();

print($posts);

?>

好的,您的代码中出现了一些不同的情况

首先,您混合了MySQLi的过程版本和面向对象版本。事实上,您正在使用MySQLi是一个巨大的优势