Skip to content
Advertisement

Insert PHP into code web design without a large block of code. Solved [closed]

I am fairly new to PHP/SQL I have been lightly playing with it for a year or so and I decided to start getting into it more.

First question I guess would be, is inserting into web design. Is there ways to place it so I am not putting in a block of code more like one line through an include? I would like it so a admin user database table isn’t coded in my home.php. I am probably asking super simple questions I just don’t like having the below in my code and it getting hard to find things.

 <div class="w3-card w3-col s3 w3-light-grey w3-border w3-padding">

        <h4 class="w3-center w3-teal">User Database</h4>

        <table class="w3-table-all">
            <th>Name</th>
            <th>Email</th>
            <th>Status</th>
        <?php
            $conn = mysqli_connect("localhost", "root", "", "registration");
            // Check connection
            if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
            }
            $sql = "SELECT username, email, user_type FROM users";
            $result = $conn->query($sql);
            if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
            echo "<tr><td>" . $row["username"] . "</td><td>"
            . $row["email"]. "</td><td>" . $row['user_type'] . "</td></tr>";
            }
            echo "</table>";
            } else { echo "0 results"; }
            $conn->close();
        ?>

        </table>

    </div>

Advertisement

Answer

The simplest solution is to move the PHP code to another file say “helper_functions.php”. So the result would look something like this :

helpers.php
<?php 

    function print_rows(){
        // Your code goes here
    }
?>

And in your view file just include the helpers file and call the function like so :

<div class="w3-card w3-col s3 w3-light-grey w3-border w3-padding"> 
    <h4 class="w3-center w3-teal">User Database</h4> 
    <table class="w3-table-all">   
        <th>Name</th> 
        <th>Email</th> 
        <th>Status</th> 
        <?php
            require_once("helper_functions.php");
            print_rows();  
        ?>
    </table> 
</div>

This is by no means the best solution. If you want to write much cleaner, seperated and organised code, I suggest you read about MVC architecture.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement