Vous êtes sur la page 1sur 10

PHP Back to Basics Part 7 Connecting to a MySQL Database

Gareth Downes-Powell

PHP Back to Basics Connecting to a MySQL Database


In this tutorial, we're going to look at connecting to a MySQL database using PHP. Although Dreamweaver MX contains a number of server behaviors for connecting to a MySQL database and performing database operations, these can be quite limiting and if you want to build a truly powerful website you really need to be able to hand code the database operations yourself. Once you can do this all limits are removed and you're no longer limited in what you can achieve! Before we start this tutorial, it's important to have a working MySQL server, and a username and password to work with a MySQL database. These will normally be set up by your web host.

Building a Database
Before we can look at connecting to a database with PHP, we need to first have a database to work with. Using a database tool such as PHPMyAdmin, create a new database on your MySQL server called example. We'll be using this database throughout this tutorial. If you already have an existing database that you want to use, you'll need to substitute the name of your database into the code that we'll be creating later.

Creating a table - users


Next, create a new table in the database with the name users, using the definition in the table shown below. Field Name id username name email Field Type int varchar varchar varchar Length 11 20 100 150 Extra auto_increment

You can do this directly with the following SQL: CREATE TABLE users ( id int(11) NOT NULL auto_increment, username varchar(20) NOT NULL default '', name varchar(100) NOT NULL default '', email varchar(250) NOT NULL default '', PRIMARY KEY (id) ) TYPE=MyISAM; Here we have created a table with four fields. The first field, id, is used to hold a unique id number for each user. This is filled in automatically by MySQL as the field is set to auto_increment, which automatically adds the next number in the sequence as each record is added. We then have fields to hold the user's username, name and email address.

Adding Data to the Users table


Now that the users table has been created, the next step is to add some data to the table for us to work with. Add the data shown in the table below as an example to use with this tutorial.
Copyright 2004 DMXzone.com All Rights Reserved to get more go to DMXzone.com

Page 1 of 10

PHP Back to Basics Part 7 Connecting to a MySQL Database


Gareth Downes-Powell

username dmxgareth dmxbruce dmxgeorge

name Gareth Downes-Powell Bruce Lawson George Petrov

email gareth@example.com bruce@example.com george@example.com

If you wish you can add some more example records to the database, however as we now have some initial records to work with, we can move on and start looking at how to connect to the database through PHP.

Working with a MySQL database


The process of connecting to a MySQL database through PHP is fairly simple, and the same steps are always taken, no matter how you want to work with the data contained in the database. A flowchart illustrating the steps required is shown below.

Figure 1 Flowchart showing required steps for working with a MySQL database We'll now look at these steps in more detail, before we start looking at the actual code required to carry out these steps in the next section.

Copyright 2004 DMXzone.com All Rights Reserved to get more go to DMXzone.com

Page 2 of 10

PHP Back to Basics Part 7 Connecting to a MySQL Database


Gareth Downes-Powell

Connecting to the MySQL Server


The first step to working with a MySQL database through PHP is always to connect to the MySQL server. This opens up a connection between your PHP script and the MySQL server so that the script can communicate with the server using SQL. To connect to the MySQL server, you need to supply the address of the server, which is usually localhost because the MySQL server normally runs on the same physical machine as the web server. You also need to supply a MySQL username and password which has permission to connect to the server and the database you want to use. Once a connection has been opened, it stays open until it's closed again. When your PHP code opens a connection to the server, it's important to check that the connection has been opened successfully before your code continues.

Select Database
Once a connection to the MySQL server has been opened, you next need to tell the MySQL server which database you want to work with. This is important as typically a MySQL server has more than one database running on it. It's important that your user details in MySQL allow you to connect to the database that you want to use.

Execute MySQL Query


Once you have connected to the MySQL server and selected your database, you can now run an SQL query against the database. SQL is the heart of communicating with the database, and you will probably be familiar with SQL SELECT queries which allow you to read records from a database. However, everything you need to do with the database in the database can be done by executing an SQL query whether it's updating, deleting or adding new records. If you're new to SQL, DMXzone have a beginner's track in premium content by Rudy Limeback, a SQL guru. When a connection has been opened, you can execute as many SQL queries as you require until the connection is closed.

Close Server Connection


The final step in the process is to close the connection to the MySQL server. Its important to do this once the connection is no longer needed by your code, as each connection takes up memory and resources on the server, and these aren't freed until the connection to the server is closed. If connections are left open and never closed, eventually these will build up and can swamp the server and stop your code from working. Now that we have looked at the processes involved, we will look at the PHP commands that are used with each of these processes.

Copyright 2004 DMXzone.com All Rights Reserved to get more go to DMXzone.com

Page 3 of 10

PHP Back to Basics Part 7 Connecting to a MySQL Database


Gareth Downes-Powell

PHP Commands for Working with the MySQL database


In this section, we're going to go back over the processes involved in working with a MySQL databases and we are going to look at the PHP commands and code required to perform each step.

Connecting to the MySQL Server


To connect to the MySQL server we use the PHP mysql_connect() command, which takes the following parameters. $dbLink = mysql_connect($hostname,$username,$password); To use the mysql_connect() command, you pass the hostname of the server (normally localhost), and the username and password to connect to the server. If the connection is successful then a link to the open connection is returned by the command, and this is needed for all future commands that want to use that connection. As previously mentioned above, it's important to check that the connection has opened successfully, otherwise all future database commands will fail. To connect to the MySQL server, and check the connection has succeeded you can use the following code: $host = "localhost"; $username = "username"; $password = "password"; $dbLink = mysql_connect($host,$username,$password); if(!$dbLink){ die ("Could not connect to the MySQL Server"); } Remember to change the username and password to the ones assigned to you by your web host, as well as the host name.

Select Database
The next step is to tell the MySQL server which database we want to work with, which we use with the mysql_select_db() command which has the following parameters. mysql_select_db($database_name,$dbLink); Here we pass the name of the database that we want to use, and the link to the open database connection returned by the mysql_connect() command. To connect to our database named example, you would use the following code.
Copyright 2004 DMXzone.com All Rights Reserved to get more go to DMXzone.com

Page 4 of 10

PHP Back to Basics Part 7 Connecting to a MySQL Database


Gareth Downes-Powell

mysql_select_db("example",$dbLink) or die("Cannot Select Database");

Execute SQL Query


Now that we have opened a MySQL connection and selected a database, we can now run a MySQL query which we can do with the mysql_query() command. This takes the parameters shown below. $result = mysql_query($query,$dbLink); To run the query we pass the SQL statement in $query, and a link to the open database connection. The mysql_query() command returns a result which indicates whether or not the command has succeeded, and in the case of a SELECT query a link to the records retrieved by the query is returned. As an example, we can use the following code: $sql = "SELECT * FROM users"; $result = mysql_query($sql,$dbLink) or die("SQL query failed to execute"); $result now contains a link to the records returned by the SQL query. We'll look at how to work with these records in the next section.

Close Server Connection


The final step in the process is to close the database connection once we've finished working with it, which we do with the mysql_close() command which accepts the following parameters. mysql_close($dbLink); The only parameter that we need to pass is the link to the open database connection that we want closed. All that we need to close the connection is shown below: mysql_close($dbLink); Now that we've looked at all the code needed for each step in the process, we are going to move on and start looking at some examples.

Working Examples
In this section, were going to look at a selection of example which use the code above, and show how to perform the main database functions such as reading records, adding records, updating records and deleting records.

Reading Records from a Database

Copyright 2004 DMXzone.com All Rights Reserved to get more go to DMXzone.com

Page 5 of 10

PHP Back to Basics Part 7 Connecting to a MySQL Database


Gareth Downes-Powell

First, were going to look at reading records from a database which we can do by executing a normal SQL SELECT statement. Open a new PHP page in Dreamweaver MX, and save the page as example1.php. Next, add the following block of code to the page body in code view. <?php $host = "localhost"; $username = "username"; $password = "password"; $dbLink = mysql_connect($host,$username,$password); if(!$dbLink){ die ("Could not connect to the MySQL Server"); } mysql_select_db("example",$dbLink) or die("Cannot Select Database"); $sql = "SELECT * FROM users"; $result = mysql_query($sql,$dbLink) or die("SQL query failed to execute"); $numRecords = mysql_num_rows($result); for($i=0;$i < $numRecords;$i++){ $records[] = mysql_fetch_assoc($result); } echo "<pre>"; var_dump($records); echo "</pre>"; mysql_close($dbLink); ?> Code Block 1 Example Code to read records from a database Remember to change the username and password in the code above to connect to the database, and also the host name if required. You can see in the code above that most of it we have already seen before, and there is only a small amount of extra code required to read the records returned by the SQL query and display them. We'll look at this new code again below: $numRecords = mysql_num_rows($result); for($i=0;$i < $numRecords;$i++){ $records[] = mysql_fetch_assoc($result); } First, we use a new command, mysql_num_rows() and pass it the result obtained from the mysql_query() command. This command tells us how records are returned by the SQL SELECT query, and we store this number in $numRecords. Next, we use a for loop which runs once for each record returned by the SQL SELECT query. Each time round the loop we use the PHP mysql_fetch_assoc() command passing it $result returned by the mysql_query() command. The mysql_fetch_assoc() command reads in one record at a time in the form of an associative array, where the arrays keys are the fieldnames from the database table. We place each record array in an array called $records. Once the for loop has completed, $records will hold an array for each record returned by the SELECT statement.
Copyright 2004 DMXzone.com All Rights Reserved to get more go to DMXzone.com

Page 6 of 10

PHP Back to Basics Part 7 Connecting to a MySQL Database


Gareth Downes-Powell

echo "<pre>"; var_dump($records); echo "</pre>"; Next, we use the var_dump() command as shown above to display the records on the page, formatted using HTML <pre></pre> tags. When the code is run, the output shown below will be displayed. array(3) { [0]=> array(4) { ["id"]=> string(1) "1" ["username"]=> string(9) "dmxgareth" ["name"]=> string(20) "Gareth Downes-Powell" ["email"]=> string(18) "gareth@example.com" } [1]=> array(4) { ["id"]=> string(1) "2" ["username"]=> string(8) "dmxbruce" ["name"]=> string(12) "Bruce Lawson" ["email"]=> string(17) "bruce@example.com" } [2]=> array(4) { ["id"]=> string(1) "3" ["username"]=> string(9) "dmxgeorge" ["name"]=> string(13) "George Petrov" ["email"]=> string(18) "george@example.com" } } You can see that the array in $records contains three separate arrays, each consisting of one record, and that the arrays keys contain the fieldnames corresponding to the relevant field data.

Adding Records to a Database


We're now going to look at adding records to the database, which uses an SQL INSERT INTO statement, the format of which is shown below. INSERT INTO tablename (fieldname1,fieldname2,fieldname3) VALUES ('value1','value2','value3')
Copyright 2004 DMXzone.com All Rights Reserved to get more go to DMXzone.com

Page 7 of 10

PHP Back to Basics Part 7 Connecting to a MySQL Database


Gareth Downes-Powell

We are going to insert a new user into the users table using the following SQL: INSERT INTO users (username,name,email) VALUES ('dmxfred','Fred Smith','fred@example.com') Open a new PHP page in Dreamweaver MX and save it as example2.php. Add the following code to the page body in code view. <?php $host = "localhost"; $username = "username"; $password = "password"; $dbLink = mysql_connect($host,$username,$password); if(!$dbLink){ die ("Could not connect to the MySQL Server"); } mysql_select_db("example",$dbLink) or die("Cannot Select Database"); $sql = "INSERT INTO users (username,name,email) VALUES ('dmxfred','Fred Smith','fred@example.com')"; $result = mysql_query($sql,$dbLink) or die("SQL query failed to execute"); mysql_close($dbLink); ?> As usual, change the username and password shown above to your MySQL username and password. As you can see from the code above, the code is exactly the same as we have looked at so far, we have just changed the SQL that is executed. Once you have run example2.php in your browser, the new record will have been inserted. You can check this by opening example1.php in your browser which shows all the records in the users table and you can see the new record.

Modifying Records in a Database


To modify records in a database we use an SQL UPDATE statement which uses the following format. UPDATE tablename SET fieldname1 = 'value1', fieldname2 = 'value2' WHERE fieldname3 = 'value3' We are going to modify fred's email address from fred@example.com to fredsmith@example.com, which we can do with the following SQL UPDATE users SET email = 'fredsmith@example.com' WHERE username='dmxfred'

Copyright 2004 DMXzone.com All Rights Reserved to get more go to DMXzone.com

Page 8 of 10

PHP Back to Basics Part 7 Connecting to a MySQL Database


Gareth Downes-Powell

Open a new PHP page in Dreamweaver MX and save it as example3.php. Next, switch into code view and add the following code to the page body in code view. <?php $host = "localhost"; $username = "username"; $password = "password"; $dbLink = mysql_connect($host,$username,$password); if(!$dbLink){ die ("Could not connect to the MySQL Server"); } mysql_select_db("example",$dbLink) or die("Cannot Select Database"); $sql = "UPDATE users SET email = 'fredsmith@example.com' WHERE username='dmxfred'"; $result = mysql_query($sql,$dbLink) or die("SQL query failed to execute"); mysql_close($dbLink); ?> As always, remember to change the MySQL username and password in the code above. Save the page and open it in your browser. Next open example1.php, and you will see that fred's email address has been changed. As usual you can see that we use the same skeleton code, it's just the SQL statement that has changed.

Deleting a Record from the Database


The final example that we are going to look at is deleting a record from the database, which we can do with the following SQL. DELETE FROM tablename WHERE fieldname = 'value' We are going to delete fred's record from the table, so we will use the following SQL: DELETE FROM users WHERE username='dmxfred' Open a new PHP page in Dreamweaver MX, and save it as example4.php. Add the following code to the page body in code view. <?php $host = "localhost"; $username = "username"; $password = "password"; $dbLink = mysql_connect($host,$username,$password); if(!$dbLink){
Copyright 2004 DMXzone.com All Rights Reserved to get more go to DMXzone.com

Page 9 of 10

PHP Back to Basics Part 7 Connecting to a MySQL Database


Gareth Downes-Powell

die ("Could not connect to the MySQL Server");

mysql_select_db("example",$dbLink) or die("Cannot Select Database"); $sql = "DELETE FROM users WHERE username='dmxfred'"; $result = mysql_query($sql,$dbLink) or die("SQL query failed to execute"); mysql_close($dbLink); ?> Run the page in your browser, and then open example1.php and you can see that fred's record has been deleted. You can see from these examples that its actually quite easy to work with a MySQL database using PHP, as the code hardly changes no matter what you want to do to the data.

Summary
In this tutorial, we first looked at the processes involved in connecting to a MySQL database through PHP. We then looked at the PHP commands which are used to connect to the database and then execute the database queries and finally close the database connection again. In the second part of this tutorial we looked at some working examples of the PHP code needed to read records from a database, and add, edit and delete records in the database.

Copyright 2004 DMXzone.com All Rights Reserved to get more go to DMXzone.com

Page 10 of 10

Vous aimerez peut-être aussi