mysql fetch array php 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 );
}
$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);
?>