0

I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.

I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array

$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);  
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$type_zagon = 1;
$id_kurat = 1;
$usid = 78;

$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status 
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));

    $gyvuliu_array = array();

    while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
        $gyvuliu_array[] = $num;
    }

    $array_encode = json_encode($gyvuliu_array);
?>              
    <script>
        $('.surinkti_produkcija_paserti_gyvulius').click(function() {
            var gyvuliai_fermoje = '<?php echo $array_encode; ?>';
            var gyvuliu_array = [1,2,3,4,5,6,7,8,9];

            for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
                console.log(gyvuliu_array[i]);
            }

            // DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
            for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
                console.log(gyvuliai_fermoje[i]);
            }                       
        });
    </script>

I guess something is bad with the $num variable but I'm not sure.

EDIT: I've changed the second for loop and it looks like it's working:

for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) { 
    console.log(gyvuliai_fermoje[i]);
}

But I'm not sure if it's ok they aren't in the same row. http://prntscr.com/ft4i9m

EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?

4
  • I think you need to use bindColumn instead of fetchColumn to make $num automatically update after a fetch() call. Commented Jul 8, 2017 at 10:10
  • And console.log(gyvuliai_fermoje) Commented Jul 8, 2017 at 10:11
  • Thank you guys, combined these 2 things it worked pretty well. But there is a little thing I noticed: why where is a number "37" and all array items are strings, not numbers? prntscr.com/ft4glu Commented Jul 8, 2017 at 10:17
  • 1
    The number "37" means the browser's console is logging the exact same thing 37 times, and grouped them together. The reason they're strings instead of numbers is because $num is probably a string. If you're 100% sure it will always be a number, you can cast it to (int)$num when adding it to $gyvuliu_array. Commented Jul 8, 2017 at 10:25

4 Answers 4

1
var gyvuliai_fermoje = <?php echo $array_encode; ?>;

You have to remove quotes, why? If you put the value in quotes that mean var gyvuliai_fermoje is a string not an array

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

2 Comments

If I remove them, number "37" disappears but now it shows very strange result: prntscr.com/ft4h8c
That's how it should look, that's how the console logs a Javascript array of strings. What you had before was the console logging a string that looks like an array of strings (37 times).
0

Could You please try this once

 $stmt1 = $pdo->prepare("SELECT GROUP_CONCAT(num) as nums FROM tb_zagon_id WHERE status = :status 
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
 $stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));
 $row = $stmt1->fetch(); 
 $array_encode = json_encode(explode(",",$row["nums"]));
?>
 <script>
    var gyvuliai_fermoje = <?php echo $array_encode; ?>;
    $('.surinkti_produkcija_paserti_gyvulius').click(function() {
        var gyvuliu_array = [1,2,3,4,5,6,7,8,9];

        for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
            console.log(gyvuliu_array[i]);
        }

        // DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
        for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
            console.log(gyvuliai_fermoje[i]);
        }                       
    });
 </script>

1 Comment

Thank you for your answer, I think I've already found the solution :)
0

Try this

var gyvuliai_fermoje = <?php echo json_encode($array_encode, JSON_HEX_QUOT | JSON_HEX_APOS); ?>;

1 Comment

Thank you for your answer, I think I've already found the solution :)
0

Problem solved! :) For future visitors, combined all this stuff you guys said, we have this code:

// PDO Connection
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; 
    charset=utf8mb4', $db_user, $db_password);  
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Prepared statement with placeholders
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");

// Binding query result to the $num variable (1 is the first column)
$stmt1->bindColumn(1, $num);

// Executing query and replacing placeholders with some variables
$stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));

// Creating a PHP array
$gyvuliu_array = array();

// Fetching through the array and inserting query results using $num variable ((int) makes sure a value is an integer)
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
    $gyvuliu_array[] = (int)$num;
}

// Encoding PHP array so we will be able to use it in the JS code
$array_encode = json_encode($gyvuliu_array);
?>
<script>
    var gyvuliai_fermoje = <?php echo $array_encode; ?>;

    for (var i = 0; i < gyvuliai_fermoje.length; i++) {
        // Stuff you would like to do with this array, access elements using gyvuliai_fermoje[i]
    }
</script>

I hope it will help you to understand how to use a PHP array in the JS code in PDO :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.