1

I have a 1 file with html,php and javascript. Normally in php you would perform a query like this. This is good and i want to keep.

 <?php
     $sql = "SELECT * FROM voedingsmiddelen";
     $result = mysqli_query($conn, $sql);
   ?>

And then you would use this php to get the 'name' fields. This outputs "name|age|sex|birthdate|". This part below i want to do in javascript.

$count = 0;
while($row = mysqli_fetch_assoc ($result)) {

    $fieldinfo = mysqli_fetch_field_direct($result,$count);
    echo $fieldinfo->name;
    $count++;
}

This is what i came up with but i get stuck here. I want an alert with 'name' and alert with 'sex' and alert with 'birthdate' from the database.

var arraylength=<?php echo sizeof($result)+1; ?>;
        var i=0;
        while(i<arraylength){
            //what goes here i dunno
             alert(idunnohow[i]);

          i++;
        }

Is this possible? And how?

1 Answer 1

2

Try encoding your PHP data using json_encode(). That's all it takes.

var array = <?php echo json_encode( mysqli_fetch_all( $result, MYSQLI_ASSOC ) ) ?>;
Sign up to request clarification or add additional context in comments.

2 Comments

what kind of array is this and how do i get things out of there? alert(array[0]) does not work.
mysqli_fetch_all() is actually replacing the while-loop found in your example: it's returning an array of associative arrays with the latter representing single record of database matching your query. To see the result you might try appending console.log( array ); after the line given above and see the result for yourself by checking Javascript console of browser. I bet it's an array of objects each containing the fields per record as properties with either field's value.

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.