KexAri
KexAri

Reputation: 3977

Array to string conversion error with json_encode

I have a connect function for my MySQL database like so:

function connect() {

        $config = parse_ini_file('../../config.ini');

        // Try and connect to the database
        self::$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);

        //Check if both are bools and FALSE === checks type and equality
        if(self::$conn === false) {

            header("HTTP/1.1 500 Internal Server Error");
            header("Content-Type: application/json");
            $response = array("Response"=>"Failed to connect to the database");
            echo "json_encode($response)";
            die();

        }


    }

I am having an issue when I do json_encode (for the fail connection). I get the error : Notice: Array to string conversion in /var/www/html/somesite.co/public_html/API/index.php on line 47
json_encode(Array)

Really have no idea why I'm getting this error. I have encoded and echo'd and array like this before with no issues. Could someone give me some pointers to what I might be doing wrong please?

Upvotes: 2

Views: 7687

Answers (1)

pinkal vansia
pinkal vansia

Reputation: 10300

You are getting this error as you are trying to echo an array. And you don't wrap a function call in quotes.

replace

echo "json_encode($response)";

with

echo json_encode($response);

Upvotes: 5

Related Questions