Connecting and Authenticating


Since the nature of programming to a relational database management system is specific to each server (unless you are using an abstraction layer, such as PEAR DB), we will focus our code on using MySQL. Before we connect to our MySQL database server, we will quickly talk about how PHP and MySQL interact.

Sequence of Events

Chapter 1, "Getting Started with PHP,"mentioned that requests for PHP scripts first go to your web server (which recognizes them as PHP script requests) and then have the PHP language engine execute the requested script. Similarly, in Chapter 9, "Designing and Creating Your Database," we showed how programs can connect directly to database servers and spent most of the chapter using a client program to access and manipulate our data.

We will now combine the two actions and have our PHP scripts, which are requested from a client program, connect to the database server and interact directly with it. The web server sees the request for a file with the .php extension and tells the PHP processor to begin operating on that file. The script in turn makes a request to the MySQL server, which processes the request and returns the result to the script. After processing the information from the database, the script returns the appropriate output to the client program, as shown in Figure 12-1.

Figure 12-1. A series of connections from client to database, via the PHP language engine.


As we showed briefly in Chapter 9, there is a common sequence of events you follow when connecting to a database. There are a few additional steps within PHP, which we will list now:

1.

Connect to the database server.

2.

Authenticate the user with username and password.

3.

Select the database to use.

4.

Set the character set for the connection (if necessaryit is for MySQL).

5.

Perform operations on database relations.

6.

Clean up any resources returned to you by PHP.

7.

Close the connection.

We will perform the first three steps simultaneously with the new mysqli extension. What is new is that we will actually insert some code in PHP to clean up results from various operations and queries.

Making the Connection

To connect to a database server, we need the following information:

  • The host name or IP address of the server to which we wish to connect.

  • The username and password of the database user that we will use.

  • The name of the database on which we will be performing our operations.

With this information in hand, we can write our first line of code to connect to a database using the mysqli class provided by the mysqli extension. We pass our three pieces of information to the constructor for this class:

 <?php   $conn = new mysqli('hostname', 'username', 'password',                      'databasename'); ?> 

For example, if we were to connect to our message board database example from previous chapters, we could execute the following (assuming the database is on the same machine as our web server):

 <?php   $conn = new mysqli('localhost', 'mbadmin', 'password',                      'MessageBoard'); ?> 

If this connection does not work, we see a warning or an error sent to the output stream that tells us why:

 Warning: mysqli::mysqli() [function.mysqli]: Access denied   for user 'mbuser'@'localhost' (using password: YES) in   /home/httpd/www/phpwasrc/chapter11/connect.php on line 37 

This is not optimal error handling. We would like to be able to have more control over how we display errors to the user. To do this, we will use the @ operator (covered in Chapter 2, "The PHP Language") to suppress these error messages and use the mysqli_ connect_errno function instead. This function returns 0 when there is no error on the connection, or returns an error code when there is a problem.

 <?php   $conn = @new mysqli('localhost', 'mbadmin', 'password',                       'MessageBoard');   if (mysqli_connect_errno() != 0)   {     //     // get the text of the error message from MySQLi     //     $message = mysqli_connect_error();     echo <<<EOM   <p>     I'm sorry, there was an internal error and we were unable     to connect to the database server for the message boards.     The error message was:   </p>   <p><em>$message</em></p> EOM;   }   else   {     // otherwise, connection was fine, continue processing...     // when done, close connection:     $conn->close();   } ?> 

We also used the mysql_connect_error function to fetch the text error message for the failed connection. Please note that these messages are likely to be in the language of your database engine (English) and of little use if you are going to be displaying pages in other languages. Thus, we always prefix such system errors with text in the appropriate language for our users. Note that we call this an internal error in the text displayed to the users, since it most certainly is. The user should never have to worry about connecting to the database or the reasons why such an operation would fail. This is our responsibility as developers and maintainers of the web application.

Setting the Connection Character Set

By default, many of the database extensions in PHP connect to the server using the ISO-8859-1 (US English) character set. However, since we are working mostly with UTF-8 strings in our code and our databases, we need to be sure that the connection to our database is set up as such.

In MySQL, this is done by executing the following query in your code:

 SET NAMES 'utf8'; 

To do this from within code, we use the query method on the mysqli object:

 $conn->query("SET NAMES 'utf8'"); 

The query method takes the query to execute and adds the trailing semicolon for us.




Core Web Application Development With PHP And MYSQL
Core Web Application Development with PHP and MySQL
ISBN: 0131867164
EAN: 2147483647
Year: 2005
Pages: 255

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net