Search code examples
phpcsssqlinline-styles

Position data pulled from SQL vertically in PHP


I have pulled user data from a SQL table, but I want to position the data vertically as I would with ex. table-cell. Since I did this in PHP, I cannot figure out how I could do this. Also, I couldn't figure out a way to add CSS to it, so I added some in-line CSS to the whole 'echo'. Here is my code:

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "shopping_list_users";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT id, username, name, surname FROM users";
    $result = $conn->query($sql);

    if ($result !== false && $result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<p style='font-size: 2em; text-shadow: 0px 5px 12px #333333; text-align: left; font-size: 40px; margin: 30px; margin-top: 35px; font-weight: bold'>" . 
                 "ID: " . $row["id"]. "<br>",
                 "Username: " . $row["username"]. "<br>",
                 "Name: " . $row["name"]. "<br>",
                 "Surname: " . $row["surname"]. "<br>";
        }
    } else {
        echo "0 results";
    }
    $conn->close();
?>

Here is what it looks like

As I said, I want to align the $row data vertically, next to their respective "titles" (ID, Username, Name, Surname).


Solution

  • This is one of the cases where using a table really is justified. So do this:

    while($row = $result->fetch_assoc()) {
        echo '<table>';
        echo "<tr><td>ID:</td><td>" . $row["id"]. "</td></tr>";
        echo "<tr><td>Username:</td><td>" . $row["username"]. "</td></tr>";
        echo "<tr><td>Name:</td><td>" . $row["name"]. "</td></tr>";
        echo "<tr><td>Surname:</td><td>" . $row["surname"]. "</td></tr>";
        echo '</table>';
    }
    

    Or, if you really want to avoid this, use definition lists, like that:

    while($row = $result->fetch_assoc()) {
        echo '<dl>';
        echo "<dt>ID:</dt><dd>" . $row["id"]. "</dd>";
        echo "<dt>Username:</dt><dd>" . $row["username"]. "</dd>";
        echo "<dt>Name:</dt><dd>" . $row["name"]. "</dd>";
        echo "<dt>Surname:</dt><dd>" . $row["surname"]. "</dd>";
        echo '</dl>';
    }
    

    The key is, you won't achive your goal without additional markup. And these two ways are the correct ways to do this.

    The table solution will automatically fit the first column to the needed width of the largest element (in your case "Username:"), if you don't define it with CSS otherwise. I am not that familiar with definition lists, but there sould be proper ways to get a good solution with CSS.

    Edit: To get <dt> and <dd> on the same line, see here.