In our previous set of articles, we've created a simple 2 page website that allows users to submit comments about the page they were looking at. In this article, we're going to show you how to print all of the comments that users have left for a page.


Step 1. Create our SQL Query to grab all comments

In order to display comments on a page, we first need to know what comments to show. When we setup our site we created two pages, and each page was assigned a unique id number. This ID number will be used to gather comments for that specific page. For example, when the user is on page 1, we'll select all of the comments in the database assigned to page "1".

If you're not familiar with SQL, you can use phpMyAdmin to help write your SQL command. To do this:

  1. Log into cPanel and click the phpMyAdmin icon
  2. In the left menu, first click your database name and then click the table to work with. If you're following our example, we'll first click on "_mysite" and then "comments".
  3. Click "Search" in the top menu
  4. Enter 1 for the "Value" of "articleid" and then click "Go"
    create-sample-select-command-using-phpmyadmin-use-search
  5. After running the search, phpMyAdmin will show you all comments that belong to article 1, as well as the SQL syntax you can use to select those comments. The code provided is:
    SELECT * FROM `comments` WHERE `articleid` =1 LIMIT 0 , 30
    our-sample-select-query-from-phpmyadmin


Step 2. Setting up our PHP code to SELECT our comments

Now that we have our sample SQL query, we can use it to create the php code that will print all comments on a page. Below is the example code that we created. If you're not familiar with php, any line that begins with a // is a comment, and comments are used by developers to document their code. In our example, we have quite a few comments to help explain what the code is doing, but keep in mind that most scripts do not have as many comments.

<?

// At this point in the code, we want to show all of the comments
// submitted by users for this particular page. As the comments
// are stored in the database, we will begin by connecting to
// the database
 
// Below we are setting up our connection to the server. Because
// the database lives on the same physical server as our php code,
// we are connecting to "localhost". inmoti6_myuser and mypassword
// are the username and password we setup for our database when
// using the "MySQL Database Wizard" within cPanel

$con = mysql_connect("localhost","inmoti6_myuser","mypassword");
 
// The statement above has just tried to connect to the database.
// If the connection failed for any reason (such as wrong username
// and or password, we will print the error below and stop execution
// of the rest of this php script

if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
 
// We now need to select the particular database that we are working with
// In this example, we setup (using the MySQL Database Wizard in cPanel) a
// database named inmoti6_mysite

mysql_select_db("inmoti6_mysite", $con);

// We now need to setup our SQL query to grab all comments from this page.
// The example SQL query we copied from phpMyAdmin is:
// SELECT * FROM `comments` WHERE `articleid` =1 LIMIT 0 , 30
// If we run this query, it will ALWAYS grab only the comments from our
// article with an id of 1. We therefore need to update the SQL query
// so that on article 2 is searches for the "2", on page is searches for
// "3", and so on.
// If you notice in the URL, the id of the article is set after id=
// For example, in the following URL:
// http://phpandmysql.inmotiontesting.com/page2.php?id=2
// ... the article id is 2. We can grab and store this number in a variable
// by using the following code:

$article_id = $_GET['id'];

// We also want to add a bit of security here. We assume that the $article_id
// is a number, but if someone changes the URL, as in this manner:
// http://phpandmysql.inmotiontesting.com/page2.php?id=malicious_code_goes_here
// ... then they will have the potential to run any code they want in your
// database. The following code will check to ensure that $article_id is a number.
// If it is not a number (IE someone is trying to hack your website), it will tell
// the script to stop executing the page

if( ! is_numeric($article_id) )
  die('invalid article id');

// Now that we have our article id, we need to update our SQL query. This
// is what it looks like after we update the article number and assign the
// query to a variable named $query

$query = "SELECT * FROM `comments` WHERE `articleid` =$article_id LIMIT 0 , 30";

// Now that we have our Query, we will run the query against the database
// and actually grab all of our comments

$comments = mysql_query($query);

// Before we start writing all of the comments to the screen, let's first
// print a message to the screen telling our users we're going to start
// printing comments to the page.

echo "<h1>User Comments</h1>";

// We are now ready to print our comments! Below we will loop through our
// comments and print them one by one.

// The while statement will begin the "looping"

while($row = mysql_fetch_array($comments, MYSQL_ASSOC))
{

  // As we loop through each comment, the specific comment we're working
  // with right now is stored in the $row variable.

  // for example, to print the commenter's name, we would use:
  // $row['name']
  
  // if we want to print the user's comment, we would use:
  // $row['comment']
  
  // As this is a beginner tutorial, to make our code easier to read
  // we will take the values above (from our array) and put them into
  // individual variables

  $name = $row['name'];
  $email = $row['email'];
  $website = $row['website'];
  $comment = $row['comment'];
  $timestamp = $row['timestamp'];
  
  // Be sure to take security precautions! Even though we asked the user
  // for their "name", they could have typed anything. A hacker could have
  // entered the following (or some variation) as their name:
  //
  // <script type="text/javascript">window.location = "http://SomeBadWebsite.com";</script>
  //
  // If instead of printing their name, "John Smith", we would be printing
  // javascript code that redirects users to a malicious website! To prevent
  // this from happening, we can use the htmlspecialchars function to convert
  // special characters to their HTML entities. In the above example, it would
  // instead print:
  //
  // <script type="text/javascript">window.location = "http://SomeBadWebsite.com";</script>
  //
  // This certainly would look strange on the page, but it would not be harmful
  // to visitors

  $name = htmlspecialchars($row['name'],ENT_QUOTES);
  $email = htmlspecialchars($row['email'],ENT_QUOTES);
  $website = htmlspecialchars($row['website'],ENT_QUOTES);
  $comment = htmlspecialchars($row['comment'],ENT_QUOTES);
  
  // We will now print the comment to the screen
  
  echo "  <div style='margin:30px 0px;'>
      Name: $name<br />
      Email: $email<br />
      Website: $website<br />
      Comment: $comment<br />
      Timestamp: $timestamp
    </div>
  ";
}

// At this point, we've added the user's comment to the database, and we can
// now close our connection to the database:
mysql_close($con);

?>

As stated earlier, we purposely include many comments to help explain what the code was doing. While the example code above looks like a lot of work, if we strip out all of the comments, the code looks more like:

<?

$con = mysql_connect("localhost","inmoti6_myuser","mypassword");
 
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
 
mysql_select_db("inmoti6_mysite", $con);

$article_id = $_GET['id'];

if( ! is_numeric($article_id) )
  die('invalid article id');

$query = "SELECT * FROM `comments` WHERE `articleid` =$article_id LIMIT 0 , 30";

$comments = mysql_query($query);

echo "<h1>User Comments</h1>";

while($row = mysql_fetch_array($comments, MYSQL_ASSOC))
{
  $name = $row['name'];
  $email = $row['email'];
  $website = $row['website'];
  $comment = $row['comment'];
  $timestamp = $row['timestamp'];
  
  $name = htmlspecialchars($row['name'],ENT_QUOTES);
  $email = htmlspecialchars($row['email'],ENT_QUOTES);
  $website = htmlspecialchars($row['website'],ENT_QUOTES);
  $comment = htmlspecialchars($row['comment'],ENT_QUOTES);
  
  echo "  <div style='margin:30px 0px;'>
      Name: $name<br />
      Email: $email<br />
      Website: $website<br />
      Comment: $comment<br />
      Timestamp: $timestamp
    </div>
  ";
}

mysql_close($con);

?>


Step 3. Placing our php code into our pages

We now have our php code that will display comments to the screen. In a previous article, we explained how to use php's include function to reuse code, and we will continue to use this method to use our php code.

To incorporate our php code:

  1. Create a file named display_comments.php
  2. Paste in the sample code above
  3. Update both page1.php and page2.php to include display_comments.php by using:
    <? include("display_comments.php"); ?>
    towards the bottom of the page where you want to display comments.

After performing the steps above, our page1.php file now looks like this:

<? include("manage_comments.php"); ?>

<h1>This is page1.php</h1>

<div><a href='page2.php?id=2'>Click here</a> to go to page2.php</div>

<div style='margin:20px; width:100px; height:100px; background:blue;'></div>

<? include("display_comments.php"); ?>

<? include("formcode.php"); ?>

After testing our two pages, you can see that each page shows only the comments that were added to that particular page:

http://phpandmysql.inmotiontesting.com/page1.php?id=1

http://phpandmysql.inmotiontesting.com/page2.php?id=2

page1.php-with-comments page2.php-with-comments
Continued Education in Course 205: Using PHP to create dynamic pages
You are viewing Section 7: How to use PHP to connect to and retrieve data from MySQL
Section 6: Reviewing sample PHP code that interacts with a MySQL Database
Did you find this article helpful?

We value your feedback!

Why was this article not helpful? (Check all that apply)
The article is too difficult or too technical to follow.
There is a step or detail missing from the instructions.
The information is incorrect or out-of-date.
It does not resolve the question/problem I have.
How did you find this article?
Please tell us how we can improve this article:
Email Address
Name

new! - Enter your name and email address above and we will post your feedback in the comments on this page!

n/a Points
2014-07-02 3:40 am

Am a programmmer who would wish to have a text box similar to this of yours, that is were users can edit their text. I would be very grateful if you help me either with codes or how to write it. Thankyou in advance

Staff
17,716 Points
2014-07-08 2:49 pm
Hello Simon,

Thanks for the question. I'm not sure what you're asking exactly, but the code provided above shows how to create the query to the database. If you're trying to create a text editor in PHP, that's a very different task. We don't provide a tutorial to do that. However, there are many solutions already available for this. If you want a good third-party solution, check out TinyMCE. You can probably find a good instructional on programming a text editor by simply searching with a your favorite search engine. However, most of the entries on the subject suggest using existing solutions.

I hope that helps to answer your question! Please let us know if you require any further information.

Regards,
Arnel C.
n/a Points
2014-07-08 2:04 pm

very good

n/a Points
2014-07-22 9:03 am

HI, please help me

In stock file have following fields 

-SKU

-Model these 5 field from xml file 

-Quantity

-status

-price

-special price(have a formula for this)

-shipping cost(have a formula for this)

-allow cod(have a formula for this)

we are doing manually importing daily in our admin page.but we need automatically for reducing time. I have loaded xml file data to database(mysql 5.6).but now am struck next step is what? how to import from database.Am using php.So please help me.I need guide for this

Staff
20,113 Points
2014-07-22 11:50 am
Hello Roopa,

I am unsure exactly of what you are asking. It sounds as if you have gotten XML data into the database. I am unsure what you are looking to happen after that. Please understand that we do not take on coding projects and any coding samples we give are very simple. Many will need to be enhanced or modified to perform specific functions.

Kindest Regards,
Scott M
n/a Points
2014-07-27 4:05 am
Excellent Article!! It is very simple to understand and easy to follow steps. Best article ever I have found on the web.. Great work!! Thank you so much!!
n/a Points
2014-07-30 5:56 am

Thank you so much for this helpful tutorial series, I've always wanted to get into PHP but it just made my mind boggle. Your articles have been so informative and easy to follow. Please do you have any more????

n/a Points
2014-08-03 4:03 am

excuse me i have an unfaimler problem with php documents.

i am excuting right query for selecting data from the database and for inseting data.

and they excuting well no error .

but data is not fatching from database and not inserting into database. i have writen your code also and many other. mysql service is also runing.

please answer me as soon as possible.

 

Staff
20,113 Points
2014-08-04 10:35 am
Hello Ali,

Have you had the query print to the screen so you can check the queries that are running? Also, are you checking the return values for the queries to see if they are failing?

Kindest Regards,
Scott M
n/a Points
2014-08-14 2:51 am

hi guys am also working on a project and am stuck at this point where i want to search an employees details from the database using their personal numbers as my primary key in the database.

its a single form which has several buttons for ADD,DELETE,UPDATE and SEARCH..... This will all be carried out by the Administrator ...... please kindly help me , the SEARCH BUTTON is just driving me crazy dont know if its in the coding or the database (phpmyadmin)

Staff
20,113 Points
2014-08-14 9:02 am
Hello Mike,

It is impossible to diagnose an issue without code to see what is going on. And even then we can only spot syntactical or programmatic errors. Configuration errors, if there are any, are impossible to spot without server access.

You may be able to find out the issue by printing out the query variable on the page so you can see the exact query being sent to the database. Once you get that, take it to phpmyadmin and play with it until you get the results you want. After determining the exact query you need, change the code so it creates the query in the proper manner. It will then be able to pull up the data for you.

Kindest Regards,
Scott M
n/a Points
2014-08-14 9:45 am

<div id="content">

<p>Carry out activities on the Employee Details!</p>

<form name="frmLogin" method="post" onsubmit="return validateForm();" >

 

        <strong>P_NO:</strong>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="text" id="txtPno" name="txtPno" placeholder=""  size="25" required>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <button type="submit" SIZE="40" name="search" class="btn btn-info" onclick="disable_text(text);">LOOK</button><br><br>

<strong>F_name:</strong>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="text" id="txtFname" name="txtFname" placeholder="" size="25" required><br><br>

<strong>S_name:</strong>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="text" id="txtSname" name="txtSname" placeholder="" size="25"required><br><br>

<strong>Department:</strong>

<select name="Department" size="1">

<option value="ICT">ICT</option>

<option value="ACCOUNTS">ACCOUNTS</option>

<option value="INVESTMENT & BUSINESS  ">INVESTMENT & BUSINESS</option>

<option value="PLANNING">PLANNING</option>

<option value="SUPPLIES & PROCUREMENT">SUPPLIES & PROCUREMENT</option>

<option value="ADMINISTRATION">ADMINISTRATION</option>

<option value="REGISTRY">REGISTRY</option>

<option value="AUDITRY">AUDITRY</option>

</select> <br><br>

<strong>Password:</strong>&nbsp&nbsp&nbsp&nbsp <input type="text" id="txtPassword" name="txtPassword" placeholder="" size="25"  required><br><br>

<strong>Balance:</strong>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="text" id="txtBalance" name="txtBalance" placeholder="" size="25" required><br><br>

<strong>Forward:</strong>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="text" id="txtForward" name="txtForward" placeholder="" size="25"  required><br><br>

<strong>Allowance:</strong>&nbsp&nbsp <input type="text" id="txtAllowance" name="txtAllowance" placeholder="" size="25"  required><br><br>

<strong>Resumption:</strong> <input type="text" id="txtResumption" name="txtResumption" placeholder="" size="25"  required>

 

 

 

<br><br><br><br>

<button type="submit" SIZE="40"name="add" class="btn btn-info" onclick="disable_text(text);">ADD</button>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp

<button type="submit" SIZE="40"name="register" class="btn btn-info" onclick="disable_text(text);">UPDATE</button>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp

<button type="submit" SIZE="40"name="register" class="btn btn-info" onclick="disable_text(text);">DELETE</button>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp

<button type="submit" SIZE="40"name="register" class="btn btn-info" onclick="disable_text(text);">SAVE</button><br><br><hr><a href="/support/top.php"><strong>HOME</strong></a>

<BR><BR><button onclick="history.go(-1);">Back </button>

        </div>

 

<?PHP

if (isset($_POST['add'])){

$fname=$_POST['txtFname'];

$sname=$_POST['txtSname'];

$department=$_POST['Department'];

$pno=$_POST['txtPno'];

$password=$_POST['txtPassword'];

$ldb=$_POST['txtBalance'];

$dbf=$_POST['txtForward'];

$ela=$_POST['txtAllowance'];

$edr=$_POST['txtResumption'];

 

mysql_query("insert into employee (F_name,S_name,Department,P_NO,Password,Balance,Bforward,Allowance,Resumption) values('$fname','$sname','$department','$pno','$password','$ldb','$dbf','$ela','$edr')")or die(mysql_error());

}

 

if (isset($_POST['search'])){

 

$result = mysql_query("SELECT * FROM `employee` WHERE `P_NO`==='$pno'");

while($row = mysql_fetch_array($result))

{

 

    echo "<input type='text' id='txtF' value='$fname' />";

    echo "<input type='text' id='txtS' value='$sname' />";

    echo "<input type='text' id='D' value='Department' />";

 

    echo "<input type='text' id='txtP' value='$password' />";

 

    echo "<input type='text' id='txtB' value='$ldb' />";

 

    echo "<input type='text' id='txtF' input value='$dbf' />";

 

    echo "<input type='text' id='txtA' value='$ela' />";

echo "<input type='text' id='txtR' value='$edr' />";

 

}

}

?> 

</form>

</body> 

 

 

thats the portion i want to work on...... the add section is working well but when i try to search for the same employees' details using the P_NO as the primary key it does not display in the textboxes that are there.

i want the same details that i insert in the database to be displayed again when i click the search button.

please help

Staff
20,113 Points
2014-08-14 11:07 am
Hello Mike,

I did see an issue with the query, it is using the === evaluator in the MySQL. MySQL does not recognize that, it simply uses a single =. Give that a try and you may see the results you are looking for.

Kindest Regards,
Scott M
n/a Points
2014-08-15 1:46 am

thanks Scott for your time. i have changed that and already got to the page and entered the P_NO but when i click the search button there is a pop up that tells me to "! fill out this field" just at the lower textboxes..... i dont understand why.

please assist  

Staff
20,113 Points
2014-08-15 8:32 am
Hello Mike,

All of your fields in the form end with "required>". This is a built in function of HTML5 that requires something to be entered in those fields before it will allow the processing to continue.

If that will be an issue, you will likely need to remove the required option and then do the validation programmatically with javascript on the front end and php on the back end.

Kindest Regards,
Scott M
n/a Points
2014-08-21 2:36 am

is there any alternate for include stament becz i try all exmple of include but no one is working.... plz help

Staff
20,113 Points
2014-08-21 7:55 am
Hello Yasir,

Try using the following format instead:
<? include 'vars.php'; ?>


Kindest Regards,
Scott M
n/a Points
2014-08-22 8:23 am

help me with the msqli version :)

Staff
20,113 Points
2014-08-22 9:12 am
Hello James,

We can certainly update the article, but if you have any questions now, please let us know so we can assist.

Kindest Regards,
Scott M
n/a Points
2014-08-23 2:35 pm
hello i create a oun website back end control pannel and admin control dash board banner management mysql database connectivity my databse is colzim please help me and  give me instruction
Staff
20,113 Points
2014-08-25 10:45 am
Hello Rajendra,

I am unsure exactly what you are asking for. Please try to rephrase your question just a bit so we can understand what you are asking and we will be happy to try and assist you.

Kindest Regards,
Scott M
n/a Points
2014-09-04 12:53 pm

Sir,

Kindly assist in me in writing a code to select data from mysql database and to the display the result in the a simple html form. Note I have done this but it is prompting an error. I want the select criterion to be available for make in html form.

The code I wrote is below.

 

<?php

 

$mysqli = new mysqli("localhost", "root", "", "godfrey1");

 

/* check connection */

if (mysqli_connect_errno()) {

    printf("Connect failed: %s\n", mysqli_connect_error());

    exit();

}

$src=mysqli_real_escape_string($con,$_POST['search']);

 

$query = "SELECT lname, fname FROM quiztest2 WHERE lname='$src';

 

if ($result = $mysqli->query($query)) {

 

    /* fetch object array */

    while ($row = $result->fetch_row()) {

        printf ("%s (%s)\n", $row[0], $row[1]);

    }

 

    /* free result set */

    $result->close();

}

 

/* close connection */

$mysqli->close();

?> 

 

Please I need you to help me edit or better still give a guide to solving this.

Hoping to hear from you soon sir.

Regards.

 

Staff
9,384 Points
2014-09-04 1:25 pm
Could you provide me with the exact error you are receiving?
n/a Points
2014-09-17 5:38 pm

Very Useful tutorial thanks!

Post a Comment

Name:
Email Address:
Phone Number:
Comment:
Submit

Please note: Your name and comment will be displayed, but we will not show your email address.

25 Questions & Comments

Post a comment

Back to first comment | top

Need more Help?

Search

Ask the Community!

Get help with your questions from our community of like-minded hosting users and InMotion Hosting Staff.

Current Customers

Chat: Click to Chat Now E-mail: support@InMotionHosting.com
Call: 888-321-HOST (4678) Ticket: Submit a Support Ticket

Not a Customer?

Get web hosting from a company that is here to help. Sign up today!