简体   繁体   English

错误在PHP中两次调用相同的功能

[英]error in calling same function twice in php

I have a function named record_list() which helps me echo fetched query from database every time I refresh/visit a page. 我有一个名为record_list()的函数,该函数可在每次刷新/访问页面时帮助我从数据库中回显提取的查询。 I tried to use this function by echoing it twice but unfortunately all my DOM elements after the script get hidden and I can't use the following divisions/lists in my HTML. 我试图通过两次回显来使用此函数,但是不幸的是,脚本隐藏后,我所有的DOM元素都无法使用,因此我无法在HTML中使用以下分区/列表。 But if I call it once it's working fine without any problem. 但是,如果我一次调用它,就可以正常工作,没有任何问题。

Apart form this I am getting this error: 除了这个我得到这个错误:

Fatal error: Call to a member function query() on a non-object 致命错误:在非对象上调用成员函数query()

record_list(): record_list():

function record_list(){
//include db configuration file
include_once("configuration.php");
try{
//MySQL query
$user_id = $_SESSION['user_id'];
$results = $mysqli->query("SELECT * FROM education_record  WHERE user_id='$user_id' ");
//get all records from add_delete_record table
while($row = $results->fetch_assoc())
    {
    echo '<li class = "col-md-4 col-xs-12 records_display" id="item_'.$row["id"].'">';
    echo '<div class="del_wrapper"><a href="#" class="del_btn" id="del-'.$row["id"].'">';
    echo '<img src="../img/removeButtonIcon.svg" height ="20px" width ="20px" border="0" />';
    echo '</a></div>';
    echo '<div class="controls group_row">';
    echo    '<div class="controls group">';
    echo        '<input disabled type="text"class="group"style="width:175px" value ="'.$row["degree_name"].'"/>';
    echo        '<input disabled type="text"class="group"style="width:175px" value ="'.$row["institute"].'"/>';
    echo        '<input disabled type="text"class="group"style="width:175px" value ="'.$row["specialisation"].'"/>';
    echo        '<input disabled type="text"class="group"style="width:100px" value ="'.$row["date_of_passing"].'"/>';
    echo    '</div>';
    echo '</div>';
    echo '</li>';
    }
}
catch (mysqli_sql_exception $e) {
   throw $e;
   die();
}
 $mysqli->close();
//close db connection


}

configuration.php: configuration.php:

<?php
$host = 'localhost';
$dbname = 'databasename';
$username = 'username';
$password = 'can-be-anything';


try {
$mysqli = new mysqli($host, $username, $password, $dbname);
} catch (mysqli_sql_exception $e) {
throw $e;
die();
}
?>

Please help me identifying this error. 请帮助我确定此错误。

This is because you have to use include("configuration.php"); 这是因为您必须使用include("configuration.php"); not include_once("configuration.php"); 不是include_once("configuration.php"); If you include_once , it will only work when the first instance of this configuration file is included in the script somewhere. 如果您包含include_once ,则仅当该配置文件的第一个实例包含在脚本中的某个位置时才起作用。

I would suggest making a class to wrap your connection saving it to a singleton state for use everywhere else in your script. 我建议创建一个类来包装您的连接,将其保存为单例状态,以供脚本中的其他地方使用。 Here is a simple example: 这是一个简单的示例:

classes/class.DatabaseConfig.php classes / class.DatabaseConfig.php

<?php
class   DatabaseConfig
    {
        private static  $singleton;

        public  function __construct()
            {
                if(empty(self::$singleton))
                    self::$singleton    =   $this;

                return self::$singleton;
            }

        public  function connect($host = "localhost", $username = "username", $password = "password", $database = "database")
            {
                // Create connection
                try {
                        $mysqli = new mysqli($host, $username, $password, $database);
                        return $mysqli;
                    } catch (mysqli_sql_exception $e) {
                        throw $e;
                        die();
                    }
            }
    }

classes/class.Db.php classes / class.Db.php

<?php
class Db
    {
        private static $singleton;
        public static function mysqli()
            {
                if(empty(self::$singleton)) {
                    $con = new DatabaseConfig();
                    self::$singleton = $con->connect();
                }

                return self::$singleton;
            }
    }

index.php index.php

<?php
// Look into using spl_autoload_register() here
include_once("classes/class.DatabaseConfig.php");
include_once("classes/class.Db.php");
// This will work
$con = Db::mysqli();

function myQuery()
    {
        // This will also work, so long as you have included the class
        // file once before this function (not necessarily in this function either)
        // is called to use
        $con = Db::mysqli();
    }

This happens because you close connection with $mysqli->close(); 发生这种情况是因为您使用$mysqli->close();关闭了连接$mysqli->close(); every time function is executed but, as @Rasclatt suggested, you open connection only once with include_once directive. 每次执行函数时,但正如@Rasclatt建议的那样,您只能使用include_once指令打开一次连接。 You may replace include_once with include or try @Rasclatt OOP approach but if you don't want to dive into OOP for some reason I suggest to separate connection operation from the function and pass it to the function as a parameter like this 您可以将include_once替换为include或尝试使用@Rasclatt OOP方法,但是如果由于某些原因您不希望陷入OOP中,我建议将连接操作与函数分开,并像这样将其作为参数传递给函数

include_once("configuration.php");

function record_list($mysqli){
    try{
    //MySQL query
        $user_id = $_SESSION['user_id'];
        $results = $mysqli->query("SELECT * FROM education_record  WHERE user_id='$user_id' ");
        //get all records from add_delete_record table
        while($row = $results->fetch_assoc())
        {
            echo '<li class = "col-md-4 col-xs-12 records_display" id="item_'.$row["id"].'">';
            echo '<div class="del_wrapper"><a href="#" class="del_btn" id="del-'.$row["id"].'">';
            echo '<img src="../img/removeButtonIcon.svg" height ="20px" width ="20px" border="0" />';
            echo '</a></div>';
            echo '<div class="controls group_row">';
            echo    '<div class="controls group">';
            echo        '<input disabled       type="text"class="group"style="width:175px" value ="'.$row["degree_name"].'"/>';
            echo        '<input disabled type="text"class="group"style="width:175px" value ="'.$row["institute"].'"/>';
            echo        '<input disabled type="text"class="group"style="width:175px" value ="'.$row["specialisation"].'"/>';
            echo        '<input disabled type="text"class="group"style="width:100px" value ="'.$row["date_of_passing"].'"/>';
            echo    '</div>';
            echo '</div>';
            echo '</li>';
        }
    }
    catch (mysqli_sql_exception $e) {
         throw $e;
         die();
    }

}

 /// You may call here record_list($mysqli) function as many times as you wish
record_list($mysqli)

 $mysqli->close();
//close db connection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM