Other Tools By Katy:

Loop Through Recordset With MySQL and PHP (MYSQLI Connection)

This is the basic syntax required to loop through a MySQL table and output the results


<?php
// Connect to your database
$conn = mysqli_connect("localhost", "username", "password", "database_name", "Port Number If Needed");

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// 2. Perform the query
$sql = "SELECT ID, Field1, Field2 FROM YourTable";
$result = mysqli_query($conn, $sql);

// Loop through Results if we have some
if (mysqli_num_rows($result) > 0) {
    echo "<ul>";
    
    // Fetch each row as an associative array
    while($row = mysqli_fetch_assoc($result)) {
        // Output the data
        echo "<li>ID: " . $row["Field1"] . " - " . $row["Field2"] . "</li>";
    }
    
    echo "</ul>";
} else {
    echo "No records found.";
}

// Close the connection (optional, as PHP does this at end of script 
// but it's good practice to tidy up)
mysqli_close($conn);
?>

If you’re using a variable to pull out specific records then you need to use a “Bind” statement. This ensures you can have and SQL injection issues. We’ve also added some basic checks to ensure we have the ID required for the select statement and that it’s a valid number:


if (isset($_GET['id'])) 
{
    $ID = (int)$_GET['id']; // Make Sure $ID is a number

    if($ID>0)
    {
        // If we have a valid ID number
        $stmt = mysqli_prepare($conn, "SELECT Field1, Field2 FROM YourTable WHERE ID = ?");
        mysqli_stmt_bind_param($stmt, "i", $ID); // "i" means the ID is an integer "s" is string
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        
        // If we expect multiple resutls, we'd use a while loop here
        while ($row = mysqli_fetch_assoc($result)) 
            {
                    echo $row['Field1'] . "<br>";
            }
    } 
    else 
    {
        echo "Invalid ID provided.";
    }
} 
else 
{
    echo "No ID specified.";
}
Disclaimer: The code on this website is provided "as is" and comes with no warranty. The author of this website does not accept any responsibility for issues arising from the use of code on this website. Before making any significant changes, ensure you take a backup of all files and do not work directly on a live/production website without thoughly testing your changes first.

Leave a Reply

Your email address will not be published. Required fields are marked *