0

I want to get a php array made by pg_fetch_all in a javascript array. But when I try to do it, firebug tells me that I'm trying to convert an array to string. Indeed, I don't understand why because both are arrays.

Here is where I create the php array :

$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);

$sql = "SELECT ".$colonne." FROM public.".$tablevar."";
$res = pg_query($sql) or die("Pb avec la requete: $sql");

$data = pg_fetch_all($res);

And here is my js code :

var array_dropdown =[<?php echo $data;?>];

And it doesn't work. Please help me !

2 Answers 2

3

PHP Arrays 101: Arrays in a string context are the literal word Array:

$x = array(1 => 2);
echo $x; // ouputs "Array"

You need to use json_encode():

var array_dropdown = <?php echo json_encode($data); ?>;

json_encode guarantees that whatever you pass in to the encode function will be output as syntactically valid javascript. Note the lack of [] around the above code - json_encode handles all of that for you.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, it works (I don't have exactly what I wanted but it works fine ;) ). Thank you :)
0

Assume this as your PHP array

$array = array('foo' => 'bar');

The JS part:

var array = <?php echo json_encode($array); ?>;

Comments

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.