Home > Tutorials > PHP > Database I-O

Database I-O

Accessing a database isn't just for storing numbers and compiling statistics (although it is certainly useful doing that). A database can also be used to store user information (such as logins and passwords), posts in the case of a forum, or articles in the case of a blog. You could even go really crazy and store your entire site as a database, simply using PHP to extract the necessary information. Of course, before you get any of this information you will need to connect to the database.$connection=mysql_connect(servername, username, password); mysql_select_db(database_name,$connection); servername is the location of the database - usually "localhost" will be it. username and password are exactly what you think they'd be - the username and password to access the database. If there is a failure in connecting to the database for some reason (such as incorrect login credentials), mysql_connect will return false. After we are connected, we run mysql_select_db to select the actual database (as there can be many different databases on a server). We pass in the name of the database (database_name) and $connection, and we are ready to run queries: $query="<MySQL query>" $result=mysql_query($query);

Finally, we will want to access each row of our results - which we do using the following bit of code: while ($row=mysql_fetch_array($result)) { <Code for this specific row> } row will be an associative array, with keys being the names of each of the result columns - so if you have a database table named "PEOPLE" which looks like this:

FNameLNameAge
AlexSmith29
BonnieJohnson35
CarlosWilliams18
DanielleJones13
EricaBrown49
FredDavis62

And your MySQL query was "SELECT * FROM PEOPLE", one iteration of mysql_fetch_array() might look something like:

  • $result['FName']='Alex';
  • $result['LName']='Smith';
  • $result['Age']=29;

For the complete set of MySQL-related functions, see the PHP manuaul at www.php.net.

<<PreviousNext>>

Comment on this page:

Your information Name:
Email:
Hide Email?
Enter the 5 characters shown.
Request another image.
Prove your human:
Comments Overall page rating:

Comments

No one has commented on this lesson yet. You can be the first!