2019/09/27

PHP and MySQL - Trying out "mysqli_fetch_assoc()".

This is a quick experiment on using "mysqli_fetch_assoc()" to retrieve data from MySQL database and display the retrieved data.

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php

$conn = mysqli_connect("localhost", "root", "", "sensors");

$query = "SELECT * FROM t_viewname";

// Get the number of row in the result
$number_filter_row = mysqli_num_rows(mysqli_query($conn, $query));

echo "No. of Row: ".$number_filter_row;
//echo $number_filter_row;
echo "<br>";

// mysqli_query() -> Perform queries against the database.
// For example:
//      mysqli_query($con,"SELECT * FROM Persons");
//      mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)");

$result = mysqli_query($conn, $query);

// Reference:
// https://stackoverflow.com/questions/14456529/mysqli-fetch-array-while-loop-columns

$post = array();
while ($row = mysqli_fetch_assoc($result)) {
    $post[] = $row;   
}

foreach ($post as $row) { 
    foreach ($row as $element) {
        echo $element.", ";
    }
    echo "<br>"; 
}

?>

Note, see below for the explanation on why there is no index inside the while loop.

Ref.: https://stackoverflow.com/questions/9105419/generate-array-from-php-while-loop


The Result


Reference:

mysqli_fetch_array while loop columns
https://stackoverflow.com/questions/14456529/mysqli-fetch-array-while-loop-columns

No comments:

Post a Comment