How can I populate a javascript array with values from a database using PHP?

后端 未结 5 863
走了就别回头了
走了就别回头了 2021-01-03 14:59

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)

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 15:18

    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.

提交回复
热议问题