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 set up 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”. To ensure seamless functionality like this, it’s essential to have reliable PHP hosting that supports efficient database interactions.

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:
// https://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:
// https://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:  
https://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 = "https://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="https://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>https://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:

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

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

page1.php-with-commentspage2.php-with-comments

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

  1. 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!!

     

  2. 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.

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

  4. 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.

  5. 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.

  6. 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

    1. w3schools.com is a great source for SQL, and PHP information, as well as php.net.

      Thank you,
      John-Paul

  7. 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

     

     

    1. 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.

  8. 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

    1. 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.

  9. This is a great tutorial, thanks!

    I fully completed the tutorial, but was confused by step 2 (see below), visit your first page. I just went to my webpage with the form on it and typed out a comment and pressed submit, but nothing happened.

    Where should my files be uploaded and how does the submit button know where my database is?

    Step 2 – Submit a comment on your website

    Visit your first page, https://phpandmysql.inmotiontesting.com/page1.php?id=1. It is very important that “id=1” is in the URL, otherwise our php code will not know which article the comment belongs to.

    1. You can place the files wherever you are doing your testing. The “localhost” parameter makes sure that script is using the database located in the local environment.

  10. Hi, thanks for your tutorial, it works really well and it’s been a great learning experience.

    Having got it to work with numeric ID’s, I’ve now tried to set this up with SEO ID’s (e.g. https://mywebpage.uk/blog/blog-slug). I’ve had some success, in that the url displays the blog slug and the SEO ID (blog-slug) is placed into the articleid column in the database. But the comments related to that articleid are not being displayed.

    Without wanting to cause you any hassle, do you happen to know what part of your code should be changed to, so that display_comments.php knows to display comments related to the blog-slug rather than id=n. Like I said the blog-slug does already appear in the articleid in the database.

    Thank you, Jules

    1. Hello Jules,

      Thanks for the question about the code. Unfortunately, we do not provide coding support, so we can’t provide changes to existing code on our pages. If you’re changing the qualifying value from and id number to specific “blug-slug”, then you need to change that logic in the code and change it so that you’re using a valid “blog-slug” as the condition for showing the comment. If you are unable to do that, then you may want to consult with a programmer for help in making the customization.

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

      Regards,
      Arnel C.

    1. Hi Scott,
      I get a 1064 error : “mysql_fetch_array() expects parameter 1 to be resource, boolean given” on line 45 :
      45 : echo “

    2. Hello DigitalWarrior,

      If you are using a mysql_fetch_array() then you will need to do a foreach to display them. Also if the query is returns a null response it could throw this error. Can you provide more of the code so we can investigate it further?

      Best Regards,
      TJ Edens

  11. Thank you for all your efforts in creating a remarkable hosting company. An d I intend to spread the news. 

    In ref. to insertion of comments to database tables, would you have some codes that would allow the user to include multiple comments to the same id. Thanks

    1. Hello John,

      Thank you for the kind words. We do not currently have a code tutorial for that, but we do hope to have more tutorials like this in the future that contain more features. Perhaps one like you are asking for will be among them.

      Kindest Regards,
      Scott M

  12. I follow tutorial exactly and in my comment section it does not display the actual name, email, website, etc from the database. It just displays the variable names: $name, $email, $website, etc.

     

    I’m lost…

    1. Since this is the final guide in a full tutorial series, ensure you have completed the other sections on Using PHP to create dynamic pages.

      Thank you,
      John-Paul

  13. Hello Inmotion Hosting team,

    Thanks for this 7 page tutorial. I’m really confident that i’ll be able to apply a DB to a website now.

    I did have a couple questions tho:

     

    1) How secure is this whole method from SQL injection or other attacts? I assume that its not going to stop 100.00% of attacks. Is it worth coding more PHP validations (as in not allowing “!<> … ” into a form box )? 

    2) I have your Power-Plan, from what I understand I would have to have one of your Techs apply an SSL certificate. If I were to get an SSL certificate how would this be applied to my forms/user-log-ins? I guess I don’t understand how a SSL would make my pages more secure if I’m the one doing the coding.

    If your replys are as good as your phone-suport then I’m sure I’ll be impressed!

    Thanks!

    -Connor

    1. Hello Connor,

      SQL injection occurs due to the lack of validating the input properly. If you take the input and strip it of improper text using the mysql_real_escape_string or prepared statements, then SQL injection should not be an issue. It is definitely prevented via code.

      SSL Certs are designed to secure the transmission of data to the website. It encrypts it so it cannot be read by someone who may be monitoring the traffic from the outside. This is good for logins, forms, and payment pages during transmission, but an SSL does not prevent SQL injection via forms that do not have the proper code protection in place.

      Kindest Regards,
      Scott M

    1. You are correct! We are actually in the process of coming through to update articles that are old and/or deprecated. This is definitely on our list!

    • Nice article. My problem is i’m using php, need to retreive data from 2 diferent database and check if they are equal using oracle as database.
  14. thanks for the replay im getting the idea but how the script look.

    My main concern is that the queary will be generate using the url

    https://phpandmysql.inmotiontesting.com/page2.php?id=555-5555-5555

    or any other employeedid

    How i set that in the SQL statement?

    SELECT EmployeeID FROM `tablename` WHERE `employeeID` ="HERE"

     

     

    1. Hello Joan,

      Yes, you can use the “$_GET” command in PHP with code similar to the below example:

      URL: domain.com?id=123

      $number = $_GET[“id”];

      Select * from members WHERE phone=$number;

      If you’d like to read the official PHP documentation about $_GET I’ve provided the link here: https://php.net/manual/en/reserved.variables.get.php

  15. nice guide but what i should do if i want to search for sample

    in my database under the column “EmployedID”

    using the url

    https://phpandmysql.inmotiontesting.com/page2.php?id=555-5555-5555

    Where 5555-5555-5555 is a EmployedID in my database table

     

    1. Hello Joan,

      You basically need to use phpmyadmin to access your database and then do a specific search. If you’re not familiar with SQL, then you guide above to generate the specific search. If you’re looking in a particular column, the select statement needs to specify the column. You can find an example of how to specify a colum in an SQL statement here. So instead of “*” in the select statement, it would look like:

      SELECT EmployeeID FROM `tablename` WHERE `employeeID` =”5555-5555-5555″

      If you wanted everything in the database then “EmployeeID” would be set “*” after Select.

      I hope this helps to answer your question, please let us know if you require any further assistance.

      Regards,
      Arnel C.

  16. Hi guys, I am trying to add products to my car, but I can’t get the id_client from the db,neither the product_id 🙁 I don’t know what to do. I have started in all the pages the session_start(). That’s the error:

    Username=alexa

    Notice: Undefined index: id_client in C:\xampp\htdocs\pw\web\adauga_cos on line 20

    id_client=

    Notice: Undefined index: id_client in C:\xampp\htdocs\pw\web\adauga_cos on line 38

    Notice: Undefined index: id_produs in C:\xampp\htdocs\pw\web\adauga_cos on line 38

    Eroare insert!

    Thanks! 🙂

     

     

     

    <?php

    session_start();

    //require_once(‘config.php’);

    ?>

     

    <div align=”center”><h1><font color=”red” size=”10″>

    <br /><br /><br /><br >

    <?php

     

    $con=mysqli_connect(“localhost”,”root”,””,”pw”);

    if(mysqli_connect_errno())

        {

          echo “Faild to connect to MYSQL: “.mysqli_connect_errno();

         }

     

        // obtine id_client cunoscandu-se username-ul

    $q = “SELECT id_client FROM `client` WHERE utilizator = ‘”.$_SESSION[‘user’].”‘”;

    $result = mysqli_query($con,$q) or die(“Eroare la selectare id_user”);

        echo “Username = ” . $_SESSION[‘user’];

    echo “id client =”. $_POST[‘id_client’];

     

     

     

    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);

    // se verifica daca cantitatile nu sunt introduse aiurea

    $query2=”SELECT stoc FROM produs WHERE id_produs=”.$_POST[‘id_produs’];

    $result2=mysqli_query($con,$query2) or die(“eroare la selectare stoc/id_produs!”);

        $row2=mysqli_fetch_array($result2,MYSQLI_ASSOC);

    if($_POST[‘cantitate’]>$row2[‘stoc’])

             echo “Nu avem acest numar de produse disponibil!”;

        else if($_POST[‘cantitate’]==0)

             echo ‘Trebuie sa introduceti cel putin un produs!’;

        else if($_POST[‘cantitate’]<0)

            echo ‘Ati innebunit? Cum sa cumparati mai putin de un produs?’;

        else

    //inserare in cos

    {

    $query=”INSERT INTO cos VALUES (“.$_POST[‘id_client’].”, “.$_POST[‘cantitate’].”, “.$row[‘id_produs’].”)”;

    mysqli_query($con,$query) or die (‘Eroare insert!’);

    header(‘Location: cos.php’);

    }

    ?>

    </div></font>

     

     

     

    1. Hello Ale,

      Unfortunately we are unable to set up a test environment and troubleshoot code. If you have questions on a specific error, then we may be able to help. For your situation, you need to find out if the id is being grabbed. If not, you need to trace back in the code to find out why and where it is broken.

      Kindest Regards,
      Scott M

  17. Hello everyone, I seem to be stuck. I’m attempting to display the comments
    on pages 1 & 2, but I keep getting an error message:

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in line 23
    This is line 23:
    while($row = mysql_fetch_array($comments, MYSQL_ASSOC))

    I’m new at this, and feel like I’m missing something completely obvious.
    Can you help me?

    1. Hello Matt,

      The code “while($row = mysql_fetch_array($comments, MYSQL_ASSOC))” is correct, so it may be cause by other things in your code. You will want to test the result variable and print out any error code on the screen. You can check out the forum thread here for more information on how to do that.

      Kindest Regards,
      Scott M

  18. Thanks Mr scoot for replying.

    Actually the work flow of what i want it is like sending mail to multiple email addresses. but my is inserting into a table

    To | Subject | message |

    by looping through the emails collected from a email input field separated by comma inserting to a table to get this output in fig1.0

    but the email arrays collectec from the input field is taking the list of emails as ONE(1) ELEMENT  of the array like this

    Array [0]=> ’email1, email2, email3,email4′;

    instead of

    Array [0]=>’email1′;

    Array [1]=>’email2′;

    Array [2]=>’email3′;

    Array [0]=>’email4′;

     

     

    fig1.0

    id

    To

    subject

    message

    1

    Email1

    Multiple mailing

    My message content

    2

    Email2

    Multiple mailing

    My message content

    3

    Email3

    Multiple mailing

    My message content

    4

    Email4

    Multiple mailing

    My message content

    5

     

    Email5

    Multiple mailing

    My message content

     

     

  19. NOt so sofie. am a learn too just like you but here is how to do it

    first way: do SELECT * FROM tablename

    then you echo them out by:

    <?php  echo $row[‘name of colum’]?> eg

    <?php  echo $row[‘id’] ?>

    <?php  echo $row[‘name’] ?>

    <?php  echo $row[‘surname’] ?>

    <?php  echo $row[‘username’] ?>

    etc but here is the best waay

    do $Selectall=”SELECT * FROM tablename”;

    while($row = mysql_fetch_array($Selectall) or die(mysql_error())){
               
               
                $id=$row[‘ID’];
                $to_who=$row[‘to_who’];
                $from_who=$row[‘from_who’];
                $subject=$row[‘subject’];
                $message=$row[‘message’];
                $time=$row[‘time’];
                $open=$row[‘open’];
                $recipientDelete=$row[‘recipientDelete’];
                $senderDelete=$row[‘senderDelete’];
               

    echo $row[‘id’];

    echo $row[‘from_who’];

    echo $row[‘to_who’];

    echo $row[‘subject’]; //ect

    }

     

  20. good day Mr scott, and Everyone please i need your help.

    this is my situation;

    <input type=”email” name=”email[]”/> // field for the email

    $email=$_POST[’email’]; // this is collected from input field as “email[]” as array

    $subject=$_POST[‘subject’];

    $message=$_POST[‘text’];

    i want insert to a table.

    $email[0] // first element of the array

    $suject // content of the filed

    $message // the text of the field

    to a row1 in the table, so also

     

    $email1] // first element of the array

    $suject // content of the filed

    $message // the text of the field

    row 2 etc until the element is exusted.

    please  can some one help me with this?

    1. Hello Joseph,

      What exactly is your question?We are not able to provide custom coded solutions but are happy to answer individual questions. Where in the code are you having an error?

      Kindest Regards,
      Scott M

  21. thank you so much for your tutorial. my data is being inserted into the table, yet I keep getting the following error: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in/home/a2650603/public_html/pages/display_comments.php on line 20.  

    my full php code is as follows: <?

     

    $con = mysql_connect(“mysql12.000webhost.com”,”mydb”,”mypassword”);

     

    if (!$con)

    {

      die(‘Could not connect: ‘ . mysql_error());

    }

     

    mysql_select_db(“a2650603_news”, $con);

     

    $article_id = $_GET[‘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);

     

    ?>

    1. Hello,

      Typically this error has to do with the query string. See if you can run that string against the database and if it errors out, you will need to correct it.

      Kindest Regards,
      Scott M

  22. Hi. I understand that you do not provide codes here. Can you please direct me then on how to display a row data from mysql. i have the code to display in a select item at least one column from mysql database. once the select option is set/an item has been selected, it display in textboxes the row data that corresponds to the selected item. thank you

    1. Hello sofie,

      Thank you for contacting us. Like any coding solution, there are many ways to accomplish this. But, typically you would have to select the row you want to display, then echo it out. If you are having trouble coding this for your specific site, you may want to consider consulting a developer.

      Thank you,
      John-Paul

  23. Please, i am trying to write a code to fetch data from mysql database, and displaying them in categories. bellow is what i have done so far:

    <?php

    include “storescripts/connect_to_mysql.php”;
    $dynamicList = “”;
    $sql = mysql_query(“SELECT * FROM products ORDER BY date_added DESC LIMIT 8 “);
    $productCount = mysql_num_rows($sql); // count the output amount
    if ($productCount > 0) {
        while($row = mysql_fetch_array($sql)){
                 $id = $row[“id”];
                 $product_name = $row[“product_name”];
                 $price = $row[“price”];
                 $date_added = strftime(“%b %d, %Y”, strtotime($row[“date_added”]));
                 $dynamicList .= ‘<div class=”col-sm-3″>
                                        <div class=”product-image-wrapper”>
                                            <div class=”single-products”>
                                                <div class=”productinfo text-centre”>
                                                <a href=”product_details.php?id=’.$id.'” class=”btn btn-default”><img src=”/Piata/inventory_images/’.$id.’.jpg” width=”176″ height=”220″ alt=””>
                                                <h2>?’.$price.'</h2>
                                                <p>’.$product_name.'</p>
                                                </a>
                                                <a href=”#” class=”btn btn-default”></a><a href=”#” class=”btn btn-default add-to-cart”><i class=”fa fa-shopping-cart”> </i>Add to cart</a></div>
                                               
                                            </div>
                                        </div>
                                      </div>’;
        }
    } else {
        $dynamicList = “We have no products listed in our store yet”;
    }
    mysql_close();
    ?>

    1. Hello Dotun,

      We unfortunately do not provide coding support, as this beyond our scope of support. However, we do try to point you in the right direction or to a source that might provide an answer. Try checking out this site. It will definitely at least verify the data retrieval portion of what you’re asking.

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

      Regards,
      Arnel C.

  24. good day Mr Scotte,

     sir please i need you to help me with a code, am working on my mailing system everything is moving preety well, i appreciate.

    now have created the inbox table, php script to fetch data belonging to a user, what i want now is that when aa user click the subject or message link in his inbox, it slide down displaying the content of that message in his inbox. please i need ur help badly.

    thanks for being dere God bless

    1. Hello joseph,

      Thank you for contacting us. We are happy to help, but do not know a way to affect the recipients inbox. This is because it is up to their client to handle mail once received, such as Outlook, Mac mail, etc.

      Thank you,
      John-Paul

  25. hello. i want to ask did button submit can fetch data from database n insert the fetch data into new table in database? if it can. can u give example code. bcz i don’t know how to do it 

    1. Hello Chitra,

      When pulling data from the database, you can filter out what you want by using a WHERE clause at the end of your MySQL Query.

      Kindest Regards,
      Scott M

    2. Hello Chitra,

      Mostly the image file path is stored in the database and then retrieved into the code. This data is saved and retrieved just as any other text would be.

      Kindest Regards,
      Scott M

    3. Hello puteri,

      The submit button will call a php script of your choosing. You can make that code do anything you like. Unfortunately we do not have any sample code for what you ask.

      Kindest Regards,
      Scott M

  26. *Code removed by moderator*

    This is my coding am inserting values into the database,but the displaying should be done based on condition i.e.,if check-in and check-out dates are free then it has to dispaly those rooms only.

  27. How to fetch and display the images from database.

     

    please answer to my question as soon as possible.

  28. *code removed by moderator*

    this is my frontend coding please help me to connect this with my database.

            thank q in advance

  29. in database using id how to display the particular values(if i enter login form that values store in database and that value display on page)

    1. Hello Rajesh,

      I am not quite understanding what you are asking, could you give a specific scenario?

      Kindest Regards,
      Scott M

  30. TJDens here are the structure of my tables bt the php code to execute wat i want which is send and recieving of mail from another user to a particular user inbox. please help me with the code of hw all these will go.

    thanks

    CREATE TABLE [Users]

        (

          [UserID] INT ,

          [UserName] NVARCHAR(50) ,

          [FirstName] NVARCHAR(50) ,

          [LastName] NVARCHAR(50)

        )

     

    CREATE TABLE [Messages]

        (

          [MessageID] INT ,

          [Subject] NVARCHAR(MAX) ,

          [Body] NVARCHAR(MAX) ,

          [Date] DATETIME,

          [AuthorID] INT,

        )

     

    CREATE TABLE [MessagePlaceHolders]

        (

          [PlaceHolderID] INT ,

          [PlaceHolder] NVARCHAR(255)–For example: InBox, SentItems, Draft, Trash, Spam

        )

     

    CREATE TABLE [Users_Messages_Mapped]

        (

          [MessageID] INT ,

          [UserID] INT ,

          [PlaceHolderID] INT,

          [IsRead] BIT ,

          [IsStarred] BIT

     

        )

    Database Diagram: alt text

     

    1. Hello Joseph,

      Thank you for contacting us. Unfortunately, there is no way for us to know if this is correct. Without knowing all the details of what you are trying to accomplish, it is impossible to give you an exact solution.

      We’re confident you can code a solution, but you will have to troubleshoot, code, and work through the solution.

      Thank you,
      John-Paul

  31. Thanks scott i realy appreciate for the feedback that am having from you guys, is a pleasure to me having a wonderful friends like you guys. have started the project(mailing system), jst creating some user table and designing the login interface for the registration. after that i will be creating tables for Mailbox etc any where am stuck i know you guys gat my back. thanks alot and God bless you allll. JOE SAY SO

     

    1. Hello Joseph,

      I would suggest mapping out the database and see how you want everything to work. After that if you need help with commands to create the tables we can help you but if you are not an experienced MySQL user then I would recommend using PHPMyAdmins Gui instead.

      Best Regards,
      TJ Edens

  32. hello John,

    thank you for your reply. actualling am working on a mailing system project and what i want the system to do is to register new user, have a loging point to log user, and user logged in will have inbox, sent message, compose message, etc and logout option. the user can be able to send message to members of the system.

    the difficulty am having is that how to structure the database to create account to each new user, login user, have him/her to send and receive message etc.

    this are the table am about to create

    student table: name, surname, registration number, email,dateofbirth, gender, student_id.

    user atble:username, password, user_id

    inbox:id, from,subject,timestamp,message.

    draft table:id, draft.

    sent message:to,subject,message,id.

    contact table:nameid.

    course table:course name,department,id.

    before i forget each user will be givivng a format of hw thier username will look like.

    also i dont understand how the data flow will be like.

    i will be greatefull if my request is grant will urgency.

    thanks

    1. Hello Joseph,

      Unfortunately we are not able to provide custom solutions. Do remember when building a relational database that you are looking to connect related tables with common keys. For example, you may have the user ID in the sent-message table to keep track of who sent what message. This column would not be a key column for the sent-messsage table but it is a primary key for the user table. This is a simplistic example, but one you must perform for each of the tables you want to relate.

      Kindest Regards,
      Scott M

  33. hello scott,

    plss i need ur help am working a messaging system project in my school(jst like a database table interaction) bt am finding difficult to relate my table. the following are the table below:

    student table

    department table

    staff table

    inbox

    draft

    sent_msg

    contact

    user acct.

    please help me wit the code and idea on how this is possible

    1. Hello Joseph,

      Thank you for contacting us. We are happy to help, but it is not clear what you are asking. When you say “relate my table” please provide more specific information on what you are trying to accomplish.

      Thank you,
      John-Paul

    1. Hello Asif,

      The code above shows how to get the data already. If you’re going to use a table, it will be something you format and fill with the data that you retrieve. We can’t provide that code for you. If you’re unable to code it yourself, then you may want to consult with a programmer/developer.

      Regards,
      Arnel C.

  34. Love the code was able to get everything to work. 2 questions

    Is there a way to make the most recent comments appear on top of the list just under the comment box while keeping the comment box at the very top? I placed the display code under the formcode to keep the box on top but the newest comments appear at the bottom.

    Also,

    I noticed when I leaving a comment and a thank you comes up, if refresh the page

    the comment duplicates on the html page and the database. Is there a way to prevent this?

    – –

    Note; I noticed people can click on the submit button with blank form and it will process a blank comment and store it in the data base. I can write the security code to prevent that. Just wanted people to know in case they get the occasional moron wanting to click submit 20 million times. It’d be a lot of wasted space.

    1. Hello ALex,

      Simply alter the query to retrieve and order by the timestamp in descending order.

      Kindest Regards,
      Scott M

  35. please hlep me 

    When i run the code i get Warning:

    mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\lab3.php on line 66

    This is the php code that i execute:

    //connection

    $connection=mysqli_connect( $db_localhost , $db_username , $db_userpassword , $db_name );

    if (! $connection) {

        die(“Connection failed: ” . mysqli_connect_error());

    }

     

    //select DB

    mysql_select_db($db_name);

     

    //validation

    if(isset($_POST[“id”]) && isset($_POST[“name”]) && isset($_POST[“gender”]) && isset($_POST[“email”]) && isset($_POST[“telephone”]) && isset($_POST[“picture”]))

     

    { $id=$_POST[“id”];

     $name=$_POST[“name”];

     $gender=$_POST[“gender”];

     $email=$_POST[“email”];

     $telephone=$_POST[“telephone”];

     $picture=$_POST[“picture”];

     

     //query

     $query=”INSERT INTO student values(‘”.$id.”‘,'”.$name.”‘,'”.$gender.”‘,'”.$email.”‘,'”.$telephone.”‘,'”.$picture.”‘)”;

     //echo $query;

     $result=mysqli_query($connection, $query);

     if ($result) {

        echo “New record created successfully”;

    } else {

        echo “Error: ” . $query . “<br>” . mysqli_error($connection);

     

     

     

    //echo $result;

     while($row= mysql_fetch_assoc($result))

    {

     echo $row[‘ID’];

     echo $row[‘Name’];

     echo $row[‘Gender’];

     echo $row[‘Email’];

     echo $row[‘Telephone’];

     echo $row[‘Picture’];

     

     }

    }

     

     

     

    1. Hello Walaa,

      Try putting the following code right before the while command that fetches the mysql results: “echo mysql_error()”. Pretty much something is failing to cause the query to return false instead of the row information.

      Best Regards,
      TJ Edens

  36. plz anyone i need help … i am new to php n mysql .and i hv to creat a daily planner report it wil b very great if you could help me out…

     

    1. Hello Pritesh,

      Unfortunately we are not able to provide code for custom coding solutions, however if you have specific issues with code not performing properly then we are more than happy to look into it for you.

      Best Regards,
      TJ Edens

    1. It is very interesting if you add Editing option (update) to this article and also speak about unicode for other languages.

  37. I’m using similar code to create a news blog for my site that only I write.

     

    How can I add a function to ask for a Username and Password to be checked before a post can be submitted?

    1. Hello Jof Davies,

      Thanks for the question. We don’t really provide code for this type of thing, but we can’t point you in the direction of a resource that may help. Checkout this guide on creating a login page. This should give you some direction on what you are trying to create.

      I hope this helps to answer your question, please let us know if you require any further assistance.

      Regards,
      Arnel C.

  38. hi

    i have been trying to work in my project i hope that anyone here can help in my code i cant execute the name of the column but the data in the row is already executed all i want to execute is they are line.in the field name here is my code

    <?php

    $connection = mysql_connect(“localhost”, “root”, “”); // Establishing Connection with Server

    $db = mysql_select_db(“xxx”, $connection); // Selecting Database

    //MySQL Query to read data

    $query = mysql_query(“select * from Result”, $connection);

    while ($row = mysql_fetch_array($query)) {

    echo “<b>id={$row[‘ID’]}\”>{$row[‘ProgramID’]}\”>{$row[‘ExamDate’]}\”>{$row[‘PassNat’]}\”>{$row[‘TakeNat’]}\”>{$row[‘PassFirst’]}\”>{$row[‘FailFirst’]}\”>{$row[‘CondFirst’]}\”>{$row[‘PassRetake’]}\”>{$row[‘FailRetake’]}\”>{$row[‘CondRetake’]}\”></a></b>”;

    echo “<br/>”;

    }

    $query1 = mysql_query(“select * from Result”, $connection);

    while ($row = mysql_fetch_array($query)) {

    echo “<b>id={$row[‘ID’]}\”>{$row[‘ProgramID’]}\”>></a></b>”;

    echo “<br />”;

    }

    ?>

    </div>

    <?php

    if (isset($_GET[‘ID’])) {

    $id = $_GET[‘ProgID’];

    $query3 = mysql_query(“select * from Result where ProgramID=$id”, $connection);

    while ($row1 = mysql_fetch_array($query1)) {

    ?>

    <div class=”form”>

    <h2>—Details—</h2>

    <!– Displaying Data Read From Database –>

    <span>ProgramID:</span> <?php echo $row1[‘ProgramID’]; ?>

    <span>ExamDate:</span> <?php echo $row1[‘ExamDate’]; ?>

    <span>PassNat:</span> <?php echo $row1[‘PasssNat’]; ?>

    <span>TakeNat:</span> <?php echo $row1[‘TakeNat’]; ?>

    <span>PassFirst:</span> <?php echo $row1[‘FailFirst’]; ?>

    <span>FailFirst:</span> <?php echo $row1[‘PassFirst’]; ?>

    <span>CondFirst:</span> <?php echo $row1[‘CondFirst’]; ?>

    <span>PassRetake:</span> <?php echo $row1[‘PassRetake’]; ?>

    <span>FailRetake:</span> <?php echo $row1[‘FailRetake’]; ?>

    <span>CondRetake:</span> <?php echo $row1[‘CondRetake’]; ?>

    </div>

     

     

    <?php

    }

    }

    ?>

    <?php

    if (isset($_GET[‘ID’])) {

    $id = $_GET[‘ID’];

    $query3 = mysql_query(“select * from Result where ProgramID=$id”, $connection);

    while ($row1 = mysql_fetch_array($query1)) {

    ?>

    <div class=”form”>

    <h2>—Details—</h2>

    <!– Displaying Data Read From Database –>

    <span>ID:</span> <?php echo $row1[‘ID’]; ?>

    <span>ProgramID:</span> <?php echo $row1[‘ProgramID’]; ?>

     

    </div>

    <?php

    }

    }

    ?>

    <div class=”clear”></div>

    </div>

    <div class=”clear”></div>

    </div>

    </div>

    <?php

    mysql_close($connection); // Closing Connection with Server

    ?>

    </body>

    </html>

     

    ////and here is the output all i want is  the output of ProgramID are line with the

                                                                               BSCRIM      

    sorry for my wrong grammar 🙂

     

    Click On Menu

    id=1″>BSCRIM”>2014-06-01 00:00:00″>1808″>5022″>2″>4″>0″>1″>1″>0″>
    id=3″>BSArcht”>2014-06-01 00:00:00″>1100″>1803″>1″>1″>0″>0″>0″>0″>
    id=4″>BSCE”>2014-05-01 00:00:00″>1862″>4289″>0″>1″>0″>3″>1″>0″>
    id=5″>BSCRIM”>2014-04-01 00:00:00″>4688″>13873″>14″>23″>0″>12″>116″>0″>
    id=6″>BSECE”>2014-03-01 00:00:00″>907″>2574″>0″>0″>1″>0″>4″>0″>
    id=7″>BSECE”>2014-09-01 00:00:00″>1532″>4851″>3″>6″>2″>3″>1″>0″>
    id=9″>BEEDM”>2014-01-26 00:00:00″>11120″>38377″>3″>2″>0″>13″>13″>0″>
    id=10″>BEEDT”>2014-01-26 00:00:00″>11120″>38377″>6″>1″>0″>6″>24″>0″>
    id=11″>BEEDC”>2014-01-26 00:00:00″>11120″>38377″>0″>0″>0″>0″>2″>0″>
    id=12″>BSEDH”>2014-01-26 00:00:00″>12033″>42538″>0″>1″>0″>0″>8″>0″>
    id=13″>BSEDM”>2014-01-26 00:00:00″>12033″>42538″>2″>3″>0″>5″>36″>0″>
    id=14″>BSEDT”>2014-01-26 00:00:00″>12033″>42538″>7″>1″>0″>4″>6″>0″>
    id=15″>BSME”>2014-10-01 00:00:00″>2960″>3841″>1″>0″>0″>0″>0″>0″>
    id=16″>BSEE”>2014-02-01 00:00:00″>574″>1648″>0″>1″>0″>0″>4″>0″>
    id=17″>BSEE”>2014-09-01 00:00:00″>2190″>3661″>3″>3″>0″>0″>5″>0″>
    id=19″>BEEDM”>2014-08-17 00:00:00″>25301″>70786″>97″>20″>0″>0″>27″>0″>
    id=20″>BEEDT”>2014-08-17 00:00:00″>25301″>70786″>36″>20″>0″>1″>32″>0″>
    id=21″>BEEDC”>2014-08-17 00:00:00″>25301″>70786″>14″>2″>0″>0″>3″>0″>
    id=22″>BSAg”>2011-07-01 00:00:00″>1085″>2962″>2″>1″>0″>1″>1″>0″>
    id=23″>BSCE”>2011-05-01 00:00:00″>1195″>3117″>0″>1″>0″>1″>0″>0″>
    id=24″>BEEDM”>2011-04-03 00:00:00″>5221″>33023″>3″>1″>0″>10″>36″>0″>
    id=25″>BEEDT”>2011-04-03 00:00:00″>0″>0″>2″>6″>0″>3″>20″>0″>
    id=26″>BEEDM”>”>0″>0″>0″>0″>0″>0″>0″>0″>

     

     

     

     

  39. hi i have been trying to work on a code simular to this one for some time now and i am constantly hitting the same issue nowi fell like i am banging my head onto a brick wall

    i have built  a form and i have my DB and page to show my results

    for some reason no matter which way i code the form nothing i enter into my form is reaching my DB i have tried 3 or 4 different types of tutorials to make this happen and still nothing is making it into my DB can you guys help me please

    1. Hello baxt01,

      What type of errors are you getting? Please provide the exact error text so that we may be able to assist you with any troubleshooting.

      Kindest Regards,
      Scott M

  40. hello sir! i’m very much worried how to display specific information like i have the list of students with their information in the databse what im going to display is that when i click specific student i can only view his/ her information but what i have here is all the infomation of all students from the database. im very confuse how to display only one student info. please help me

     

    example for more clear:

    STUDENT LIST’S

    Kennedy Kim (once i click this one)

    Hannah yang

    Gyle Wang

     

     

     

    (this should be the result)

    student info

    name:Kennedy Kim

    age: 19

    address: america

     

     i hope you reply my defense is on friday JAn. 30,2015 i need it as soon as possible.thank u in advance

    1. Hello M,

      To pull information on a specific student, you will structure your SQL Query to pull only for that particular student. This is normally done by looking for the student’s ID number. For exampe:

      Student ID: 101
      Last Name: Kennedy
      First Name: Kim

      Student ID: 102
      Last Name: Yang
      First Name: Hannah

      Student ID: 102
      Last Name: Wang
      First Name: Gyle

      When you click on the name, the ID would also be there (maybe a hidden field on the page) and that would be used to customize the query for the database:

      Select * from students where studentID = 101; (would bring info on Kennedy Kim)

      Kindest Regards,
      Scott M

  41. Hi, I Have created a calendar for my websites which display the events in the calendar but What I am looking for now is once the user logged in to their account I would like to display the events that the user has signed up for the events in the side of the calendar not all the events in the text box just that the user has signed up for. Do you have any ideas how do i do this by using php code?

    1. Hello David,

      I am not able to give a specific code example here as I do not know how you have coded so far and do not know your database structure, but I can provide the concept. When a user logs in, they likely have a userid. This is likely tied to the specific events the user has signed up for. On the calendar, simply only display the events that come from the database linked to that userid. This will then allow the user to only view the events they have signed up for.

      Kindest Regards,
      Scott M

  42. First off thank you so much for this tutorial! It worked perfectly!  

    I got everything to work as it should, but I’ve been trying to figure out how save words into the articleid field in the database.  I changed the type to varchar and if I go to some id=a, for example, it gives me an error: “Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/user/public_html/display_comments.php on line 18.”  It does, however, write to the database, because when I go there I can see a under articleid.  But the comments for that won’t display and the same error occurs.  How to I alter the code so I can save and display the articleid as words without getting this error?  Currently I’m limited to just numeric values.

    Thanks!

    1. Hello,

      Thanks for the question. The article provides you some basic functionality, but providing modifications for other purposes is typically beyond the scope of the support center. The articleid used in multiple locations with the code and is expected by the code to be a certain format. Since you altered it you caused a resulting “ripple effect” because multiple lines of code no longer work as per the original intent. If you want to save data, then you should add another variable that you can assign to save as a word.

      Apologies, but we cannot provide the code for your changes as it is beyond our scope., but you be might find more information by learning about PHP coding here.

      Kindest regards,
      Arnel C.

  43. This is a great tutorial!  Especially for people like myself that have no experience!    I’m looking forward to creating the various steps for my website.    I’m curious to know of it would be difficult to add in the ability for an email to be triggered to an address when someone adds a comment to the webpage?  It would be ideal if the email included the person’s name and comment but even just an email to alert me that someone has added a post would be a great benefit.    I didn’t see a tutorial for this – and I don’t know how complicated it would be to add – esp for a beginner like myself!

    1. Hey Marty,

      That is very possible, however it would take some coding knowledge to make the changes. We do not have a tutorial currently for that, but I will add it to our list as I think it would be a good addition to the articles.

      Kindest Regards,
      Scott M

  44. When i run the code i get Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\project\News.php on line 120

    This is the php code that i execute:

     

    <?php

        $con = mysql_connect(“localhost”,”beatshare”,”beatshare”);
        
        if (!$con)
        {
          die(‘Could not connect: ‘ . mysql_error());
        }
        
        mysql_select_db(“comments”, $con);

        $query = “SELECT * FROM `comments` ORDER BY id DESC “;

        $comments = mysql_query($query);

     

        while($row = mysql_fetch_assoc($comments, MYSQL_ASSOC))
        {
          $name = $row[‘name’];
          $email = $row[’email’];
          $comment = $row[‘comment’];
         
          $name = htmlspecialchars($row[‘name’],ENT_QUOTES);
          $email = htmlspecialchars($row[’email’],ENT_QUOTES);
          $comment = htmlspecialchars($row[‘comment’],ENT_QUOTES);
         
          echo ”  <div style=’margin:30px 0px;’>
           Name: $name<br />
           Email: $email<br />
           Comment: $comment<br />
         </div>
          “;
        }

        mysql_close($con);

        ?>

    1. Hello Ryan,

      When running the command from your mysql command line does it work correctly? It almost sounds like your query is returning nothing and the file was not setup to handle results that are empty.

      Kindest Regards,
      TJ Edens

  45. 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.

     

  46. 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

    1. 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

    1. 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

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

  48. 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  

    1. 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

  49. <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=”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

    1. 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

  50. 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)

    1. 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

  51. 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.

     

    1. 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

  52. 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????

  53. 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

    1. 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

    2. 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!!

    1. 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.

  54. 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

Was this article helpful? Join the conversation!

Questions about our MailChannels Deployment? We have answers and are here to help!Learn More
+