cRAN
cRAN

Reputation: 305

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. 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. 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

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:

<?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.

Upvotes: 0

Views: 2020

Answers (2)

max
max

Reputation: 2817

This happens because you close connection with $mysqli->close(); every time function is executed but, as @Rasclatt suggested, you open connection only once with include_once directive. 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("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

Upvotes: 0

Rasclatt
Rasclatt

Reputation: 12505

This is because you have to use include("configuration.php"); not 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.

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

<?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

<?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

<?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();
    }

Upvotes: 1

Related Questions