Web/ Design/ Vista

Resources for Designers & Developer

Contact Form in PHP with Validation – Part II

In part I, i covered creating a database, form and entering data with validation checks. In this part i am going to show you how to display the entered messages.

Let us get started.

Create a new file messages.php and enter the following code

<?php

$conn = '';
// connect to database
require_once('connect-db.php');
// Perform query to retrieve results from contacts table
$result = $conn -> query( "SELECT * FROM contacts" );

We created connect-db.php in part I of this tutorials. This script is used to establish a connection to database.

Check if the mysql query returned any result.

if ( mysqli_num_rows( $result ) > 0 ) {
  // show results
}

Loop through the query results. Note the use of mysqli_fetch_assoc. It is an inbuilt PHP function which returns results of a mysql query as an associative array.

echo "<ul>"; // i am using an unordered list to display results
while( $row = mysqli_fetch_assoc( $result ) ) {
   echo "<li>";
   echo "Name: " . $row["cname"]. "<br>";
   echo "Message: " . $row["msg"]. "<br>";
   echo "</li>";
}
echo "</ul>";

Finally close the mysql connection

$conn->close()

As you may have noticed, only 2 fields Name and Message are shown here – for illustration. You can show any number of fields you want. Also, very minimal markup is used to display the results. This is done on purpose so that you can add your own styling.

Full code of messages.php below

<?php

$conn = '';
// connect to database
require_once('connect-db.php');

?>

<!-- Display messages -->

<div>

<?php

    // Perform query
    $result = $conn -> query( "SELECT * FROM contacts" );

    // check if query returned any results
    if ( mysqli_num_rows( $result ) > 0 ) {

        // loop through the query results
        // mysqli_fetch_assoc function is an inbuilt php function which fetches query result as an associative array 
        echo "<ul>"; // i am using an unordered list to display the messages
        while( $row = mysqli_fetch_assoc( $result ) ) {
            echo "<li>";
            echo "Name: " . $row["cname"]. "<br>";
            echo "Message: " . $row["msg"]. "<br>";
            echo "</li>";
        }
        echo "</ul>";

     } else {
        echo "No messages found!";
     }
    
    // close the mysql connection
    $conn->close();

?>
  
</div>

That concludes part II of this tutorials.

You can download the full source code from my github repository.