How to use PHP to Connect and Retrieve Data from MySQL

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 use PHP to Connect to and Retrieve Data from MySQL.

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

Note that mysqli_fetch_array was deprecated in PHP versions below 7.0. As of 7.0, the code has been removed and replaced with mysqli_fetch-array.

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"

/*NOTE that in PHP 7.0, the mysql_fetch_array has been removed -it was previously deprecated 
in earlier versions of PHP.  You find the cod documentation here:  
http://php.net/manual/en/function.mysql-fetch-array.php */

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'];

  $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>";

// Please remember that  mysql_fetch_array has been deprecated in earlier
// versions of PHP.  As of PHP 7.0, it has been replaced with mysqli_fetch_array.  

while($row = mysql_fetch_array($comments, MYSQL_ASSOC))
{
  $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 <a href="http://php.net/htmlspecialchars" target="_blank">htmlspecialchars function</a> to convert
  // special characters to their HTML entities. In the above example, it would
  // instead print:
  //
  // <span style="color:red;"><</span>script type=<span style="color:red;">"</span>text/javascript<span style="color:red;">"></span>window.location = <span style="color:red;">"</span>http://SomeBadWebsite.com<span style="color:red;">"</span>;<span style="color:red;"><</span>/script<span style="color:red;">></span>
  //
  // 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);
  
  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

Thoughts on “How to use PHP to Connect and Retrieve Data from MySQL

  • 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!!

     

  • Nice tutorial. This tutorial is good example for retrieve a data from database using jQuery. It saved lot of time. it just made my work easier.

     

    Thanks.

  • I really thank you for this guide, i would be ungrateful not to drop atleast a comment. May God bless you so much!

  • Please i want to know how to create the article id. When do you have to add it to the page? is it when you are linking the user to the page or when the user submits a comment and you are processing it? When exactly do you add the id to the article,

    also , the article id, does it refer to the id that appears for the article in the table you have created to store articles or you can choose any id of your choice and append it to the article. Thank you.

    My question simplified: I want to know how to create the article id.

  • This post has been very useful to me. I am new to php and it was all made very easy, especially the sql injection and other security related code. Thanks once again. Please keep posting for helping the beginners.

  • That article is amazing..I have learnt so much. I have a question I have been researching on and couldn’t find a suitable answer. I am working on a project that reqquires user to search for objects on a website and it takes them to a map with markers at the locations they entered.  The database has so many objects in dfferent coodinates and only markers with the object the user is looking for should appear. I can not figure out how to convert the location to coodinates for the database search and back to coodinates that have markers on a map..I will appreciate your input.

    Bedan

  • I live in a small town where no facility of learning website building.I am making a result website but I have no idea about this. My website should contain a SEARCH PAGE and a submit button after entering roll no. To fetch the result. I have tried so many videos and tutorials but I failed every time. Can you give me code file for that? Result page should contain Roll no. ; Enrol. No. ; Name; F/H Name; Subject wise marks of 5 subjects; Total Max. Marks; Min. Marks; Total Obtained and Result.

     

    It would be a great help for me if you can also tell me where to put these code files. Thanking you

     

     

    • Hello Mukesh,

      Apologies, but we do not provide coding support, so we cannot provide the code that you seek. Your question is asking for specific code. You can modify the code that is provided within the tutorial as a start for the problem that you are trying to solve.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  • sir, how can we fetch a single record data of one db table by an unique id of other db table..

    sir….please help me

    • Hello Akash Poot Pandey,

      Thanks for the question about fetching data from one table with the unique ID of another database table. We do not provide coding support in community support, but we do try to point you in the right direction. According to this forum post the issue is related to joins.

      I hope this helps to answer your question. If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.