php fetch array code example

Example 1: print sql query result as an array php

<?php
$connection = mysqli_connect( 'localhost', 'root', 'dbPass' );
if ( !$connection ) {
    die( 'Database Connection Failed' . mysqli_error( $connection ) );
}
$select_db = mysqli_select_db( $connection, 'sample_login' );
if ( !$select_db ) {
    die( 'Database Selection Failed' . mysqli_error( $connection ) );
}
$query = 'SELECT * FROM login';

$result = mysqli_query( $connection, $query );
$stack = array();
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {
    array_push( $stack, $row );
}
//Stop the code here if you just want it as a PHP array 
//(Don't forget the PHP closing tag) if you do that though
//If you want to carry on and convert the PHP array to a JavaScript array
//Include the rest of this code

$theArray = json_encode( $stack );
print_r( $theArray );
?>
<script>
var theArray = <?php echo $theArray ?> ;
console.log(theArray);
</script>

Example 2: mysql_fetch_array php

<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Impossible de se connecter : " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
   printf("ID : %s  Nom : %s", $row[0], $row[1]);
}

mysql_free_result($result);
?>

Example 3: php fetch

while ($row = mysqli_fetch_assoc( $result)) {}

Tags:

Misc Example