Gun arves Gun arves - 7 months ago 13
PHP Question

How do I get four fields as a row in a MySQL table?

How do I get four fields as a row in a MySQL table?

Table structure:

id name
------------
1 John
2 Doe
3 M
4 King
5 Mark
6 Someone
7 Thing
8 Super


The html output should be:

John - Doe - M - King
Mark - Someone - Thing - Super


etc..

I have no code samples as I have no clue where to begin. I have over 300,000 rows.

Answer

This is what I would do:

$mysqli = database::connect(); // Get a connection
if ($result = $mysqli->query("SELECT name FROM tablename ORDER BY id ASC")) {
    $i = 0;
    $data = "";
    while($row = $result->fetch_array(MYSQLI_ASSOC)) {
        $data .= $row['name'];
        $i++;
        if ($i < 4) {
            $data .= " - ";
         } else {
            $data .= "<br />";
            $i = 0;
         }
    }
    $result->close();
}
echo $data;
Comments