2

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?

4
  • 1
    echo json_encode($response);, function should not be wrapped in quotes Commented Jul 27, 2015 at 13:05
  • 1
    echo json_encode($response); is enough, no need for ". Commented Jul 27, 2015 at 13:05
  • I thought with double quotes echo would still evaluate any functions inside? Commented Jul 27, 2015 at 13:08
  • 1
    I think only variable names are evaluated, not function calls. Commented Jul 27, 2015 at 13:10

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?> still giving me same error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.