0

I have a small problem. I would like to insert SQL table information into a predefined Javascript code. I know how it works with PHP but I have never done it with Javascript and so I need your help. I am a total beginner.

SQL Table:

Date_begin | Date_end | Text
-----------|----------|-----
03/2002    |07/2020   |test1
05/2002    |08/2020   |test2
...        |...       |...

PHP SQL Query (PDO):

<?php
    $Date_begin = $connection->query("SELECT Date_begin FROM `test_table`");
    $Date_end = $connection->query("SELECT Date_end FROM `test_table`");
    $Text = $connection->query("SELECT Text FROM `test_table`");
?>

Predefined static JavaScript Code where the Information must be put in:

<script>
    ['03/2002', '07/2020', 'test1'],
    ['05/2002', '08/2020', 'test2'],
    ....
</script>

My attempt to solve it to make it dynamic:

<script>
    var Date_begin = <?php echo $Date_begin ?>;
    var Date_end = <?php echo $Date_end ?>;
    var Text = <?php echo $Text ?>;

    begin loop
    ['XXX', 'XXX', 'XXX'], // SQL Row 1
    ['XXX', 'XXX', 'XXX'], // SQL Row 2
    ['XXX', 'XXX', 'XXX'], // SQL Row 3
    ...                    // SQL Row n
    end loop 
</script>

Now I need to generate the above lines dynamic and fill it with the SQL Information. I think I need a loop but I don't know the syntax. I also don't know if I passed the variables from PHP to JavaScript correctly.

Thanks for any help and answer.

1 Answer 1

1

At the moment, you are not fetching any data, just executing the queries. Note that you only need one query since you are fetching all the data from the same table with the same conditions (in this case, none). You can get a JavaScript array of data directly from your PHP code by using json_encode.

Your code should look something like this:

<?php
$result = $connection->query("SELECT Date_begin, Date_end, Text FROM `test_table`");
if (!$result) {
    // deal with error
}
$data = $result->fetchALL(PDO::FETCH_NUM);
?>
<script>
    var data = <?php echo json_encode($data, JSON_UNESCAPED_SLASHES); ?>
     // process data array
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that helps me a lot. There is only a small issue. It outprints the Array with "\/" instead of only "/" : [["03\/2002","07\/2020","test1"]]
@htmlandy sorry about that - you can resolve it with the JSON_UNESCAPED_SLASHES flag to json_encode. See my edit.

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.