I have to create a javascript array whose elements are fetched by php from a database. Is it possible? If so, how?
(I dont want to use ajax to do that)
Here is a solution that correctly deals with single quotes in the data:
First retrieve the database data, for example with mysqli_ functions:
$result = mysqli_query($con, $sql);
if (!$result) die(); // error handling comes here
$array = mysqli_fetch_all($result, MYSQLI_ASSOC);
Then convert it to JSON, escape single quotes and output the JavaScript:
$output = str_replace("'", "\'", json_encode($array));
echo "var array = '$output';";
Note that json_encode
escapes backslashes (as it should) by doubling them. And it is normal that it does not escape single quotes, as it cannot know the context we put it in. So when we inject it in JavaScript, wrapping it in single quotes, we are also responsible for escaping the quotes.