Evan Stoddard
Evan Stoddard

Reputation: 708

Return from mysqli_query() into array

I'm working on a project where I have a database class with some functions that may be used throughout the project. One of the functions basically executes a query and returns anything that may be a result of that query.

I want to put that return value into an array. This is because I have an error function called within the query function and want to return that as well. This is my query function:

//Execute query
function executeQuery($payload, $database){

    //Create database connection
    $con = connectDB($database);

    //execute query
    $result = mysqli_query($con, $payload);

    //Check for error
    $error = sqlErrorHandling($con);

    //Create return array
    $returnArray = array($error, $result);

    //Return result
    return $returnArray;    

}

I know that the sqlErrorHandling() function works and my connectDB() function works, but this function gives me the error: Cannot use object of type mysqli_result as array

I'm assuming that due to my putting $result in an array. Is there any way to do this?

This is the code that's giving me the error:

$result = executeQuery($databaseQuery, null);

        //Create local variables based off array
        list ($error, $result) = $result;

NOTE: I'm NOT trying to get the value of the rows in with this bit of code. It may very well be used to do so, but this is supposed to be a generic function to execute a query and then allow multiple things to be done with that query. For instance using it in mysqli_num_rows and such like that.

Upvotes: 0

Views: 1329

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157828

Your approach is all wrong.

First, this function should throw an exception in case of error, not return it
Next, you should connect once, not every time you run a query! And pass connection resource into function.

This is how it should be

function executeQuery($con, $query){

    //execute query
    $result = mysqli_query($con, $query);
    if (!$result) {
        throw new Exception($con->error);
    }

    //Return result
    return $result;
}
$result = executeQuery($con, $databaseQuery);

this way you will have your result along with proper error reporting.

Upvotes: 2

Related Questions