0

I am working on a PHP application in which I am trying mysqli instead of MySQL. Following is the code in file db_functions.php:

function get_database_connection(){
        $conn = new mysqli('localhost', 'user', 'password', 'dbname');
        if ($conn->connect_error) {
            trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
        }
        return $conn;
    }

    function execute_sql_query($query, $error_message){
        $result = "";
        $query = trim($query);
        $conn = get_database_connection();
        $result = $conn->query($query);
        $conn->close();
        var_dump($result);
        return $result;
    }

In another file index.php, I am including db_functions.php and calling execute_sql_query method. Following is the code:

$sql = "select * from employee";
    $result = execute_sql_query($sql, "");
    $tip_array = array();
    while($row = $result->fetch_assoc()){
    $uname = $row['uname'];
}

When I run this, it shows error:

Call to a member function fetch_assoc() on a non-object

halfer
  • 19,824
  • 17
  • 99
  • 186
Vishal Suri
  • 447
  • 2
  • 12
  • 32
  • Why are you closing connection `$conn->close();` in `function execute_sql_query($query, $error_message){` ?? – Nana Partykar May 11 '16 at 15:38
  • And, instead of `$result = "";` It should be `$result = array();` – Nana Partykar May 11 '16 at 15:40
  • I am closing connection to avoid mutiple connections which can create problems. – Vishal Suri May 11 '16 at 15:41
  • So, if connection will get closed how `while($row = $result->fetch_assoc()){` will work. *Just asking..* – Nana Partykar May 11 '16 at 15:43
  • I have checked by not closing connection. Still it shows the same error. – Vishal Suri May 11 '16 at 15:53
  • what did this `var_dump($result);` give you in your execute sql method? also did you try to execute the query directly in mysql console or phpmyadmin ? – Vishnu Nair May 11 '16 at 15:59
  • var_dump($result) shows following: object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(2) ["lengths"]=> NULL ["num_rows"]=> int(4) ["type"]=> int(0) } bool(false) – Vishal Suri May 11 '16 at 16:01
  • Does this answer your question? [mysqli\_fetch\_assoc() expects parameter / Call to a member function bind\_param() errors. How to get the actual mysql error and fix it?](https://stackoverflow.com/questions/22662488/mysqli-fetch-assoc-expects-parameter-call-to-a-member-function-bind-param) – Dharman Feb 19 '20 at 22:41

0 Answers0