Subscribe to our rss feed

How to Access a MySQL Database Using PHP

Posted in PHP Tutorials, Web Development Tutorials by John Ward on the August 7th, 2007

In this tutorial I will show you how to display data from a MySQL database on a web page using PHP. This is part two in our MySQL database tutorial. If you haven’t completed the first part of this tutorial you need to do that first. Part 1 is located here: Create a MySQL Database with cPanel and PhpAdmin. When you finish that tutorial, make sure you populate the database with a few entries.

I will be using Macromedia Dreamweaver (Macromedia is now owned by Adobe) to write the code for this tutorial. You can use any plain text editor (such as notepad). This tutorial will be very basic. I hope to build on it later.

First we will need to establish a connection to the database. A nice thing about using cPanel is that it will give you the connection string. Log into your cPanel Administration panel and go to your MySQL databases.
How to Access MySQL Databases using PHP

Notice the Connection Strings. We will be using the PHP connection string. Copy everything but the $dbh= from the PHP connection string and paste it into your PHP file. As you can see below, I have already added the basic HTML to the page. Simply paste the code between the open and close PHP tags.
How to Access MySQL Databases using PHP

To explain the string a little bit:
Mysql_connect – is a built in function to connect to a database
“localost” – tells the server to connect to the local database
“projectc_testuse” – this is my username for the database (be sure to replace it with yours)
” – this is where you need to type in the password for your database user
Or die – will return an error if we cannt connect to the database.
Mysql_select_db (”projectc_Test”); - select the database for use

Now that we have a connection to the database, we will need to build our query. We will be selecting everything from the TestTable we created in the previous tutorial. An asterisks (*) is a wildcard character that means all. So our query will look like this (note: I added comments. They will be in orange).

How to Access MySQL Databases using PHP

What did we do? We created a variable called query. Then we set the variable to be a MySQL query that will select everything from our TestTable.

Now we need to execute the query and display the results.

How to Access MySQL Databases using PHP

Ok. We are creating an array called $row. Using the mysql_fetch_array function we will execute our query and store it to our array so that we can write the data to the page. Echo will write whatever follows to the page.

I will break it down the echo string a little bit here is what we have (check the comments on each line).
How to Access MySQL Databases using PHP

That is it. Save this file with a .php extension. Upload the file to your web server and execute it in your browser. The results should look something like this.
How to Access MySQL Databases using PHP

That should give you a basic idea of how to execute a query and display the results. Maybe I will do a tutorial that shows you how to style those results using HTML and CSS. Until then, you guys and girls can play around with this code and see what you come up with. Feel free to make suggestions for future tutorials in the comments.

Popularity: 15% [?]

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • BlogMemes
  • Fark
  • Furl
  • Live
  • NewsVine
  • Reddit
  • Slashdot
  • StumbleUpon
  • TwitThis
  • YahooMyWeb

Go Daddy $1.99 Domains

29 Responses to 'How to Access a MySQL Database Using PHP'

Subscribe to comments with RSS or TrackBack to 'How to Access a MySQL Database Using PHP'.

  1. Robert said,

    on August 12th, 2007 at 1:39 am

    Hi I read the first tutorial for the creation and this one. Only theres one small detail missing for me. I use CPanel11 which dosent seem to include the ‘connection string’ , is there somewhere else I can find this string. The password I inserted for the user is not valid as the normal characters I supplied in the user creation.

  2. John Ward said,

    on August 12th, 2007 at 6:55 am

    Just modify the connection string example I have given. The username and password are the ones that you set up in part one. The connection string will work regardless of the cPanel version (it is a MySQL function).

  3. Tahrah Hunt said,

    on September 6th, 2007 at 11:59 pm

    This is the error message I got. Any idea what I did wrong? Page is http://www.athomeforhire.com/resumes.php

  4. Tahrah Hunt said,

    on September 7th, 2007 at 12:00 am

    I forgot to copy/paste the error message:

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/athomef/public_html/resumes.php on line 20

  5. danny spektor said,

    on September 7th, 2007 at 4:30 am

    Hi, um, im having this error, can somebody please help?

    http://dspek.ath.cx/test.php

    Parse error: syntax error, unexpected T_VARIABLE in D:\wamp\www\test.php on line 14

  6. John Ward said,

    on September 8th, 2007 at 4:20 pm

    The error codes in PHP are pretty simple to figure out (at least to know where to look). It is telling you that you have a syntax error on line 14 of your code. An unexpected variable is just that, the server didn’t expect a variable where you have one in your code. What this usually means is you have a typo or you forgot or added some punctuation. Check the code one more time for errors.

  7. John Ward said,

    on September 8th, 2007 at 4:20 pm

    I forgot. It should be around line 14, but it could be before it.

  8. steve said,

    on September 8th, 2007 at 5:22 pm

    I am trying to publish excel file tables in php so that they can be edited and saved on line. I have converted excel to mysql dump file and then imported it thru phpmyadmin and after this I am lost. How do I save the imported mysql file to php file and set up ADMIN authority to edit databaseand anyuser to read only authority.

    My server is linux and supports php and mysql. I could also have jsp if I upgrade and I read about java pages also that can be converted from excel and edited.

    Regards
    Steve

  9. mark hearne said,

    on October 5th, 2007 at 3:19 pm

    Very good article but you could also use Dreamweaver to create the connection string for you.


  10. on February 4th, 2008 at 12:00 am

    [...] tutorial is a continuation on the “How to Access a MySQL Database Using PHP” tutorial that showed you how to setup a database using phpMyAdmin and how to read data from the database [...]

  11. julie said,

    on March 6th, 2008 at 8:13 am

    Question about the connection string - isn’t it unsafe nowadays to put a username and password for the database right in the code where anyone can view the source? Is there a way to hide it?

  12. John Ward said,

    on March 6th, 2008 at 9:09 am

    PHP is a server side language. Nobody can view the source because by the time it gets to your browser the code has already been processed server. It isn’t like Javascript (which is processed by the client) where you could right click the page and hit view source and see all of the code.

  13. julie said,

    on March 6th, 2008 at 9:52 am

    Ahh - thanks for your quick reply. This tutorial was exactly what I needed - if I had one wish though, it would be to have an email confirmation sent after the user filled out the form…. but I”m working on that myself with the php books and the rest of the internet guiding me…..again, thanks so much, your tutorials were very easy to follow and didn’t make me learn more than I need to know about php!

  14. John Ward said,

    on March 6th, 2008 at 10:15 am

    emails are pretty easy with PHP. You would hav to write the logic of course, but this is what I use on one of my sites:

    $todayis = date(”l, F j, Y, g:i a”) ;

    $attn = $attn ;
    $subject = “CSSWV Contact:”.$attn;

    $notes = stripcslashes($notes);

    $message = ”
    $todayis [EST]
    Attention: $attn
    Additional Info : IP = $ip
    Browser Info: $httpagent
    From: $visitor ($visitormail)\n
    Message: $notes \n
    Referral : $httpref \n
    Heard About Us: $heardabout\n
    Other: $other\n
    “;

    $from = “From: $visitormail\r\n”;

    mail(”youremailhere, secondemailaddressifneeded”, $subject, $message, $from);

    Most of the variables are sent from the previous form. We also keep track of any referring sites by capturing it in a cookie. You would probably just need the last last. Basically you would check if the registration was successful and then send the email. I am actually working on user registration for another site.

    I have learned been working a lot with PHP lately launching a new site, but I have been too lazy to write any tutorials, lol. I go back to midnight shift at work this week, so I should be able to crank out a few tutorials.


  15. on March 19th, 2008 at 3:34 am

    nice tutorial .. dude…

  16. hafiz said,

    on May 3rd, 2008 at 8:04 am

    nice job you have done for new comers in programing.I need help about retrieving a single and selective record from database, actually I’m working for a site in which I post articles I wish all data will display from data base. Is it Possible? How can i do this? what happened when user wish to view previous articles or data. Please guide me

  17. Mark said,

    on June 11th, 2008 at 5:10 pm

    This (and your previous tutorial) is possibly the best tutorial I’ve ever followed. I am a teacher and value the importance of detail and thoroughness when explaining and documenting a task.

    I have been trying to get to grips with PHP for a long time (longer than a year, i tried asp and didn’t like it that much), you have restored my confidence in php and I will continue to look out for any tutorials you create.

    Keep them coming

    Mark

  18. John Ward said,

    on June 11th, 2008 at 6:25 pm

    @hafiz

    To receive a select row it depends on what you are looking for. You would just have to change the query to find what your are looking for. For example, if you wanted to display and article title “PHP for noobs” assuming it was store in a table called article you would: select * from article where title = ‘PHP for noobs’. Now it sounds like youa re tyring to code a content management system (aka CMS). This is obviously going to be more difficult. The way I have done it in the past is to create one php file that has an input variable. You would send the variable for which article you want to display using the link in the previous page. I think clean up the urls using .htaccess. It is a little bit complicated if you have never done it before. There are plenty of free CMS options out there if you wanted to implement them. We use Wordpress on this site but you have other options like: Drupal, Geeklog, Joomla, Mambo Open Source, PHP-Nuke, phpWCMS, phpWebSite, Post-Nuke, Siteframe, TYPO3, Xoops. Of course for some projects it is easier to build your own than to manipulate some of these. Good Luck.

    @Mark
    Thanks for the comment. Mike and I are not PHP experts by any means, but we will try to pass on what little knowledge we have. I hope to create some more PHP/MySQL coding tutorials in the future. I will try to cover the basics and include some more advanced things. It’s hard to find time to write these sometimes :) .

  19. mike schnider said,

    on July 10th, 2008 at 9:11 pm

    Thank you very much for the tutorials, it works great. Now I would love to take the next step and be able to search the database and display ID FName LName and PHON by inputting in a search field a name or last name or phone number (just like searching through a phone book).
    Thank you for your help.


  20. on July 16th, 2008 at 3:30 am

    [...] how to add a simple search box to query a MySQL database. This tutorial is a continuation of the “How to Access a MySQL Database Using PHP” tutorial. Since writing that original tutorial I have created a local WAMP test environment. I have [...]

  21. Will said,

    on August 3rd, 2008 at 4:00 pm

    Thank you so much, John. REALLY well done. I’ve been successful on three of your tutorials so far. You mentioned, “Maybe I will do a tutorial that shows you how to style those results using HTML and CSS.” Is this on TeamTutorials anywhere? I’m also trying to figure out how to return image results, but don’t know if this is possible. Thanks again!

  22. John Ward said,

    on August 3rd, 2008 at 10:52 pm

    Will,

    No I have not made that tutorial on styling the results yet. Also, to store images in the database is a little more difficult. Some people prefer to store the images in a folder and store the URL in the database. If you want to store it in the database you will probably store it in a BLOB format.

  23. Charles said,

    on August 7th, 2008 at 11:19 am

    Wonderful article, thanx for putting this up, really appreciate it, keep up the good work…

  24. NISHANT said,

    on August 20th, 2008 at 5:33 am

    i go through the first part of this tutorial but could’nt find cPannel.
    ijust select phpMyadmin from the menu of the wamp icon and create
    the database .But hou to access cPannel……

  25. John Ward said,

    on August 20th, 2008 at 6:25 am

    If you install the wamp server locally you will not have Cpanel. Cpanel is a control panel offer by a large selection of web hosts.

    On a local wamp install you can create the databases using phpmyadmin.

  26. Will said,

    on August 31st, 2008 at 5:34 pm

    Thanks, John . . . . picking up the project again. I’m trying create site that is similar to an auto classifieds site. (I’m testing a business hypothesis, but need to build this website to do so.) A programmer told me that I need to learn PHP to build a classifieds site, but integrating PHP results with images and formatting PHP results is a little, um, daunting. I’ll see if I can figure out how to store image URLs in the database–I really appreciate hints like that.

    Also, thanks for the PHP website templates tutorial. Learned a lot from it.

  27. Elena said,

    on October 5th, 2008 at 6:42 pm

    My CPanel / MySQL doesn’t show me the ‘connection string’, is there somewhere else I can find this string?

  28. Elena said,

    on October 5th, 2008 at 6:43 pm

    I am using MySQL client version: 4.1.22 where can I find the string?

  29. John Ward said,

    on October 5th, 2008 at 10:26 pm

    it’s in the tutorial. Change your projectc_testuse to your username and change password to your password

Leave a Comment