php mysql while fetch row 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: php foreach mysql result
$result_select = mysqli_query($cnx,$query_select);
$rows = array();
while($row = mysqli_fetch_array($cnx,$result_select))
$rows[] = $row;
foreach($rows as $row){
$ename = stripslashes($row['name']);
$eemail = stripcslashes($row['email']);
$epost = stripslashes($row['post']);
$eid = $row['id'];
}