PHP Use

only for RuBoard - do not distribute or recompile

PHP Use

The IMP project actively uses PHP. It takes information from the MySQL database for the current user to display the address book, and to set preferences. It also displays images and embeds PHP code in HTML pages.

In this section, I cover the concepts behind IMP's use of the MySQL database, the use of images, and the embedding of PHP within HTML pages. You will be given the opportunity to try out some of these concepts.

Database Interfacing

PHP provides database interface routines specific to the particular database you are using. Because you are using MySQL, I will cover only the MySQL API. The other databases have APIs similar in nature to MySQL, so the same concepts apply.

To use a database, you must first connect to it. When you connect to a database, you give the database your name and password. This validates you as a user and gives you privileges to particular tables which that database has.

Whenever the IMP user logs in to the system through the initial page, the database accesses are made based on the password you set in the PHP files. The IMP scripts have been carefully written to not allow the user to generically access the database.

NOTE

Because the database login and password is given in the PHP Web page, you must be careful to log in as a user that has very limited capabilities. If you log in to the database as a superuser, you invite trouble. An error in a PHP Web page can reveal your superuser login and password to any Web browser. This error might not occur except in extraordinary circumstances, and thus escape detection during initial testing.


When connected to a database, you look up data in the database and display that data on a Web page. You take input from a user in the form of Web page button clicks or fields that are filled out, and save that data into the database. This is exactly what IMP does with the address information the user enters.

Let's analyze an example Web page that connects to our MySQL database. We will use the IMP database tables that were previously set up. I will show you step by step how to connect to the database using PHP.

First, let's use the test directory because you already have a Web page there and have used it. To connect to a MySQL database, first connect to a server with the mysql_connect() function using a username and password. Change the index.php3 Web page to the following:

 <?php   printf("opening db....");   $db = mysql_connect("localhost","impmgr", "impmgr");   printf("closing db\n");   mysql_close($db);  ?> 

Save it, and bring up the Web page. I used lynx on my computer,

 [root@wmaxlaptop test]# lynx http://127.0.0.1/test/ 

and I got the following printout:

 opening db....closing db 

I wondered about this, because it seemed too easy. So I deliberately entered the password incorrectly by putting the letter s in front of the password. The result was markedly different:

 opening db....    Warning: MySQL Connection Failed: Access denied for user:    'impmgr@localhost' (Using password: YES) in    /home/httpd/html/test/index.php3 on line 3    closing db    Warning: 0 is not a MySQL link index in /home/httpd/html/test/index.php3 on line 6 

As you can see from the printout, PHP gives you the line number in error when it prints out error messages. This is not always the case, and depends in part on how well the included library code is written.

Now that you have a connection, let's put data into the database and retrieve that data. You can select the database with the mysql_select_db() function. Then you run a query on the database using mysql_query() and retrieve the results with mysql_fetch_object(), mysql_fetch_row(), or mysql_fetch_array(). Or, you can do both simultaneously with mysql_db_query(). Change the index.php3 page you are working with to the following:

 <?php   printf("opening db....<p>");   $db = mysql_connect("localhost","impmgr", "impmgr");   $result = mysql_select_db("imp",$db);   $user = "me@test.com"; $nick = "meme";   $result = mysql_query(             "INSERT into imp_addr (user,nickname) values ('$user','$nick')",              $db);   $result = mysql_query("select user,nickname from imp_addr",$db);   $rows = mysql_num_rows($result); //will be 1 in our case   for ($index = 0 ; $index < $rows; $index++)    {    $data = mysql_fetch_object($result);    printf("user = $data->user, nick=$data->nickname<p>\n");    }   printf("closing db\n");   mysql_close($db); ?> 

Look at the sequence of events in this PHP code before you load the Web page. I will walk you through each statement:

  1. The <?php tag indicates to the Web server this is a PHP script. It calls the PHP parser to work on this Web page. Without this statement, you get the PHP code displayed on your Web page.

  2. You print a line of code with the HTML tag <p>, which forces a line break. This is not necessary to connect to the database.

  3. Connect to the mysql database engine with the mysql_connect() function. As you saw before, if you have an error here, you will get an error displayed on the Web page.

  4. Select the database you want to use. This can be combined with the query function using the mysql_db_select() function.

  5. Set up the variable values that will be inserted into the database. This might have been done well before this code was ever executed. You can create a function of your own to insert data, passing in the variables to the function.

  6. Use the mysql_query() function call to send an SQL statement to the database, inserting data into the database. If the $result is FALSE, the call failed. For this demonstration, we did not check the return from the function call, but we should have. It can indicate an error with the data or database rather than the code.

  7. Again, use the mysql_query() call to ask the database for the information just inserted.

  8. Determine the number of rows returned by the SQL statement using mysql_num_rows(). You must feed this function the $result from the last query. You will typically use this with a counting variable that determines how many times you will go through a retrieval loop.

  9. The for loop is a good loop construct to use to gather data. A while loop is also good. I chose a for loop, and counted from zero to one less than the number returned from mysql_num_rows().

  10. To retrieve the rows, you have several options. Because I knew the names of the fields in this example, I used the msyql_fetch_object() function.

  11. Print the data returned from your query. I used the printf() function. It is my favorite because of being identical to the heavily used C library function of the same name.

  12. A "closing db" line is printed. This is not necessary, but is an aid in debugging. If you use print statements to aid debugging, you would typically remove them before you put your code in production.

  13. The database connection is closed using mysql_close().

Every use of a database from a Web page involves the same basic steps previously explained. When using the data retrieved from an SQL query, you can use functions other than mysql_fetch_object(). You can also use one of the following:

 mysql_fetch_array() mysql_fetch_field() mysql_fetch_lengths() mysql_fetch_row() mysql_field_name() mysql_field_table() mysql_field_types() mysql_field_flags() mysql_field_len() 

All these are described in the appendix, "PHP Language Reference."

Graphics

You can use PHP to get the size of JPEG, GIF, and PNG images. If you have the GD library installed, which is standard with Red Hat 6.x, you can also create and manipulate images.

NOTE

Version 1.6 or greater of the GD library will no longer manipulate GIF images. The holder of the patent for compressed GIF images has recently been fairly active in pursuing Web sites that use GIF manipulation programs that were created without paying patent fees.

Many people using the Internet have moved from the GIF format to the PNG format for that reason. If you need to use GIF images, you need to acquire licensed software that gives you the right to manipulate and display these images.


All the image manipulation functions provided by the GD library begin with "Image." You can draw arcs, boxes, lines, and rectangles. You can create polygons and fill them with colors. You can draw characters in various fonts. The following snippet of code draws a rectangle with a background and foreground color and places a string in it:

 $image = ImageCreate(150,30);/* create blank image */   $bkgcolor = ImageColorAllocate($image,255,255,255);/* background color */   $fgccolor  = ImageColorAllocate($image,0,0,0);/* foreground color */   ImageFilledRectangle($image,0,0,150,30,$bkgcolor);/* fill background graphics/ccc.gif */ImageString($image,1,5,5,"This is an image",$fgccolor); /* display a msg */ 

Using PHP in HTML Documents

Two approaches exist to using PHP in HTML pages (Web pages). The first approach is to create a Web page with an editor such as Microsoft's FrontPage, embedding PHP script in the page at the appropriate spots. The second approach is to dynamically generate the entire page using PHP.

Every HTML document should begin with an HTML DOCTYPE tag and a <HTML> tag and end with a </HTML> tag. With today's browsers, this is not very important, unless you are trying to use some advanced HTML features. Our test pages were generated without any HTML tags whatsoever.

If you do need to use advanced features, proper opening tags are used to notify the browser what to expect. If you wanted to use HTML version 3.2, you would need a skeleton that looks like this:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <HTML> <HEAD> <TITLE>Your Document's Descriptive Title Here</TITLE> ...  document info /heading </HEAD> <BODY> ... html document body </BODY> </HTML> 

NOTE

In actuality, the HTML, HEAD, and BODY tags are not needed in HTML version 3.2 because the browser can infer them. Adding these tags is a matter of taste. If you add them, some earlier browsers will be able to render the page more or less properly (except for tags it does not understand). The TITLE tag is required.


Assuming you are using a good Web page editor, these things will be taken care of for you. Your PHP code would typically be inserted in the HTML document body, after the <BODY> tag. Because the PHP code is typically stripped from the Web page before it is sent to the browser, you can insert PHP functions before the beginning of the HTML tags if you want.

If you want to create the entire Web page using PHP, you need to generate the HTML tags using print (or echo or printf ) statements. The above skeleton Web page could be written in PHP as follows :

 <?php  print('<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">'); print('<HTML>'); print('<HEAD>'); print('...  document info /heading'); print('</HEAD>'); print('<BODY>'); print('... html document body'); print('</BODY>'); print('</HTML>'); ?> 

It is generally much easier to generate your Web page using a good visual editor and spice it with PHP code. You do have to be careful with some editors because they might try to strip the PHP code from the Web page. If you use FrontPage, for example, it is usually best to turn on ASP style tags and use PHP that way. Otherwise you tend to have problems when re-editing the page.

only for RuBoard - do not distribute or recompile


MySQL and PHP From Scratch
MySQL & PHP From Scratch
ISBN: 0789724405
EAN: 2147483647
Year: 1999
Pages: 93
Authors: Wade Maxfield

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