David Doran Media

Search


Beginning MySQL (in PHP)

MySQL is the biggest Open-Source database available and is by far the most commonly used database in PHP projects.
Getting started with MySQL in PHP is easy provided you set it up properly and lay the ground work.

The essential information you need to start using MySQL is your server address, username and password. You should have this information from your hosting provider or you can probably use the default settings if you are running PHP on your own computer.

To really get you going I'm going to run through a real life example, so you will need to create a database & table.
If you have the MySQL management application PHPMyAdmin then great, if not I would suggest getting it as I will be using it in the examples here.
Once you have installed and/or logged on to your PHPMyAdmin account you should see a place to create a new database, unless your hosting provider has restricted you to one which you can still use for these examples.

If you can, create a new database called "myexample" like so:
Creating the database

You should now be able to select the new database via a dropdown in the left frame.
Next, create a table called "example" with 2 fields like so:
Creating the table (step1)
You will be taken to the table schema page for your new table "example", and you should fill it out like so: Creating the table (step2)

We have a database, we have a table and we have a structure.
Let's get coding:

 
<?php
//Create the MySQL Connection
$conn = mysql_connect( 'localhost', 'root', '' );
 
//Select a database to use
mysql_select_db( 'myexample' );
 
Here I have used my default MySQL settings and the example database we created. This code will connect to the MySQL server and select the database, now we will query the table like so:
 
//Insert an example bit of news into the table
$news = 'John Doe won the competition.';
mysql_query( "INSERT INTO example (NEWS) VALUES('$news')",$conn );
 
The code here INSERT's the variable $news into the table example.

Now that there is a row in the table we can display this information:

 
//Query the example news
$query_result = mysql_query( "SELECT * FROM example",$conn );
 
//Now loop through them
  while( $row = mysql_fetch_assoc($query_result) )
  {
          echo( 'ID' . $row['ID'] . ': ' . $row['NEWS'] . '<br />' );
  }
 
This code will query the example table and subsequently loop through the results displaying their information.
By placing all this code in one file you should be able to experiment with inserting different content and displaying the results in different ways.

Support Files