Académique Documents
Professionnel Documents
Culture Documents
Gareth Downes-Powell
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.
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.
Page 1 of 10
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.
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.
Page 2 of 10
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.
Page 3 of 10
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
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.
Page 5 of 10
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
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.
Page 7 of 10
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.
Page 8 of 10
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.
Page 9 of 10
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.
Page 10 of 10