How to Access a MySQL Database Using PHP
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.

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.

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

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.

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

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.

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: unranked [?]

























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.
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).
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
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
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
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.
on September 8th, 2007 at 4:20 pm
I forgot. It should be around line 14, but it could be before it.
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
on October 5th, 2007 at 3:19 pm
Very good article but you could also use Dreamweaver to create the connection string for you.
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 [...]
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?
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.
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!
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.
on March 19th, 2008 at 3:34 am
nice tutorial .. dude…
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
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
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