Jump to content

Sql data through php feed into a js hashmap


loxfear

Recommended Posts

<?php

//MySQL Database Connect
include 'sqlconnect.php';

$result = mysqli_query($con,"SELECT * FROM aktiviteter");
 
$i=0;

while($row = mysqli_fetch_array($result))
  {
        
  $id = $row['id']; 

echo
"<script>"
"var" . $row['id'] . "= [" 

"title:" . $row['title'] . 
", beskrivelse:" . $row['']
", pris:" . $row['pris'] . 
"];"
"</script>""
}

?>

this is how i would do it, but im not sureif it works, or how to chek if it works :/

Link to comment
Share on other sites

Hi,

 

stuffing data into a script element is a bad idea, because this easily leads to cross-site scripting vulnerabilities and bugs.

 

Since you're not even trying to prepare the data for the scripting context, it's almost guaranteed to blow up. For example, what if the title contains a double quote? Then obviously the whole JavaScript syntax breaks.

 

Use Ajax to load the data from PHP into JavaScript. As a simple example:

 

data_provider.php

<?php

// Use the JSON format for the data, because this can easily be parsed by JavaScript.
header('Content-Type: application/json;charset=utf-8');

$data = array(
    'x' => 'foo',
    'y' => 'bar',
);

echo json_encode($data);
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title>Ajax test script</title>
        <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    </head>
    <body>
        <!-- Put this into an external script; inline scripts suck. -->
        <script>
            $.getJSON('data_provider.php', function (data) {
                alert('The value of "x" is: ' + data.x);
            });
        </script>
    </body>
</html>
Link to comment
Share on other sites

so i want $data to be the id of the row, and the array to be filled with the information of the columns like :

$row['id'] = array(
    'Title' => '$row["title"]',
    'Beskrivelse' => '$row["beskrivelse"]',
    'Pris' => '$row["pris"]',

just dont think that would workbecaus of the id

Link to comment
Share on other sites

What wouldn't work? If you want to map each ID to the title, price etc., just make an associative array:

$data = array();
while ($row = mysqli_fetch_assoc($result))
{
    $data[$row['id']] = array(
        'title' => $row['title'],
        'pris'  => $row['pris'],
    );
}

echo json_encode($data);

Now $data looks something like this:

array(
    '42' => array(
       'title' => 'some title', 
       'pris'  => '12.90'
    ),
    '123' => array(
       'title' => 'another title', 
       'pris'  => '32.50'
    ),
    ...
)
Link to comment
Share on other sites

Or, you could do like @Jacques1 said, but without the Ajax call. If you already have the data when the page is requested, you could:

  1. Transform your PHP into an array
  2. Transform the array into json using json_encode()
  3. Use JQuery.parseJson() to create a JS object

It depends if you need the info right away a later on click or something.

I found this link that states the pros and cons of both methods (plus another one):

http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript

Link to comment
Share on other sites

Injecting PHP strings into script elements is very risky, error-prone and messy and should be avoided at all cost.

 

Whether or not this works at all depends on several different factors like the inner workings of json_encode() and the flavor of (X)HTML you're using. For example, plain HTML treats the content of script as CDATA, which means any occurence of the term “</script>” immediately closes the element, even if it's inside a JSON string. The only way to get around this is by escaping all forward slashes. The current implement of json_encode() happens to do this by default, but nothing tells us this will always be the case. On the other hand, XHTML treats script as a normal element, which means forward slashes are irrelevant, but you do have to escape the usual HTML characters.

 

And of course inline scripts are just messy and prevent the use of powerful protection mechanisms like Content Security Policy.

 

So why do it? Only to save a single request? I don't think that's worth the trouble.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.