PHP 5/MySQL Programming- P73 docx

5 125 0
PHP 5/MySQL Programming- P73 docx

Đang tải... (xem toàn văn)

Thông tin tài liệu

338 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r This chapter details the process of connecting to an MySQL database. If you’re using SQLite instead, please see appendix B on the CD for how to modify this chapter’s code to work with that alternate database. The concepts remain exactly the same, but some details change. Getting a Connection The first job is to get a connection between your PHP program and your MySQL server. You can connect to any server you have permission to use. The mysql_connect function arranges the communication link between MySQL and PHP. Here’s the connect statement from the showHero program: $conn = mysql_connect(“localhost”, “”, “”); The mysql_connect() function requires three parameters: • Server name. The server name is the name or URL of the MySQL server you wish to connect to. (This is localhost if your PHP and MySQL servers reside on the same machine, which is frequently the case.) • Username. The username in MySQL. Most database packages have user accounts. • Password. The password associated with the MySQL user, identified by username. You will probably have to change the username and password fields if you are run- ning this code on a server somewhere. I used default values that work fine on an isolated test server, but you must change to your username and password if you try this code on a production server. You can use the same username and password you use to log into MySQL, and your program will have all the same access you do. Of course, you may want more-restricted access for your programs. Create a special account, which has only the appropriate permissions, for program users. The mysql_connect() function returns an integer referring to the database con- nection. You can think of this identifier much like the file pointers you learned in chapter 6, “Working with Files.” The data connection should be stored in a variable—I usually use something like $conn—because many of the other database functions need to access the connection. TRAP HINT Choosing a Database A data connection can have a number of databases connected to it. The mysql_set_db() function lets you choose a database. The mysql_set_db() function works just like the USE command inside SQL. The mysql_set_db() function requires the database name and a data connection. This function returns the value FALSE if it is unable to connect to the specified database. Creating a Query Creating a query is very easy. The relevant code from showHero.php is reproduced here: //create a query $sql = “SELECT * FROM hero”; $result = mysql_query($sql, $conn); Begin by placing SQL code inside a variable. SQL commands entered into the SQL console or SQLyog require a semicolon. When your PHP program sends a command to the DBMS, the semicolon is added automatically, so you should not end your SQL commands with semicolons. Of course, you assign these commands within a line of PHP code, which has its own semicolon. (Sheesh!) The mysql_query() function allows you to pass an SQL command through a con- nection to a database. You can send any SQL command to the database with mysql_query(), including table creation statements, updates, and queries. The database returns a special element called a result set. If the SQL command was a query, the result variable holds a pointer to the data, which is taken apart in the TRAP 339 C h a p t e r 1 0 C o n n e c t i n g t o D a t a b a s e s w i t h i n P H P IN THE REAL WORLD Database security is an important and challenging issue. You can do a few easy things to protect your data from most hackers. The first thing is to obscure your username and password information whenever you publish your code. I removed my username and password from the code shown here. In a practice environment you can leave these values blank, but ensure you don’t have wide-open code that allows access to your data. If you need to post your code (for example, in a class situation), be sure to change the password to something besides your real password. 340 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r next step. If it’s a data definition command (the commands used to create and modify tables) the result object usually contains the string related to the opera- tion’s success or failure. Getting Field Names I am printing the data in an HTML table. I could create the table headings by hand, because I know what all the fields are, but it’s better to get the field infor- mation directly from the query. You won’t always know which fields are being returned by a particular query. The next chunk of code manages this task: print “<table border = 1>\n”; //get field names print “<tr>\n”; while ($field = mysql_fetch_field($result)){ print “ <th>$field->name</th>\n”; } // end while print “</tr>\n\n”; The mysql_fetch_field() function expects a query result as its one parameter. It then fetches the next field and stores it in the $field variable. If no fields are left in the result, the function returns the value FALSE. This allows the field function to also be used as a conditional statement. The $field variable is actually an object. You built a custom object in chapter 7, “Writing Programs with Objects.” The $field object in this case is much like an associative array. It has a number of properties (which can be thought of as field attributes). The field object has a number of attributes, listed in Table 10.1. Property Attribute max_length Field length; especially important in VARCHAR fields Name The field name primary_key TRUE if the field is a primary key Table Name of table this field belongs to Type This field’s datatype TABLE 10.1 COMMONLY U SED F IELD O BJECT P ROPERTIES By far the most common use of the field object is determining the names of all the fields in a query. The other attributes can be useful in certain situations. You can see the complete list of attributes in MySQL Help that shipped with your copy of MySQL or online at http://www.mysql.com. You use object-oriented syntax to refer to an object’s properties. Notice that I printed $field->name to the HTML table. This syntax simply refers to the name prop- erty of the field object. For now it’s reasonably accurate to think of it as a fancy associative array. Parsing the Result Set The rest of the code examines the result set. Refresh your memory: //get row data as an associative array while ($row = mysql_fetch_assoc($result)){ print “<tr>\n”; //look at each field foreach ($row as $col=>$val){ print “ <td>$val</td>\n”; } // end foreach print “</tr>\n\n”; }// end while The mysql_fetch_assoc() function fetches the next row from a result set. It requires a result pointer as its parameter, and it returns an associative array. A number of related functions are available for pulling a row from a result set. mysql_fetch_object() stores a row as an object, much like the mysql_fetch_fields() function does. The mysql_fetch_array() function fetches an array that can be treated as a normal array, an associative array, or both. I tend to use mysql_fetch_assoc() because I think it’s the most straight- forward approach for those unfamiliar with object-oriented syntax. Of course, you should feel free to investigate these other functions and use them if they make more sense to you. If no rows are left in the result set, mysql_fetch_assoc() returns the value FALSE. The mysql_fetch_assoc() function call is often used as a condition in a while loop (as I did here to fetch each row in a result set). Each row represents a row of the eventual HTML table, so I print the HTML code to start a new row inside the while loop. HINT 341 C h a p t e r 1 0 C o n n e c t i n g t o D a t a b a s e s w i t h i n P H P Once you’ve gotten a row, it’s stored as an associative array. You can manipulate this array using a standard foreach loop. I assigned each element to $col and $val variables. I actually don’t need $col in this case, but it can be handy to have. Inside the foreach loop I placed code to print the current field in a table cell. Returning to the Adventure Game Program At the end of chapter 9 you create a database for the adventure game. Now that you know how to connect a PHP program to a MySQL database, you’re ready to begin writing the game itself. Connecting to the Adventure Database Once I built the database, the first PHP program I wrote was the simplest possible connection to the database. I wanted to ensure I got all the data correctly. Here’s the code for that program: <html> <head> <title>Show Adventure</title> </head> <body> <? $conn = mysql_connect(“localhost”, “”, “”); mysql_select_db(“chapter7”, $conn); $sql = “SELECT * FROM adventure”; $result = mysql_query($sql); while ($row = mysql_fetch_assoc($result)){ foreach($row as $key=>$value){ print “$key: $value<br>\n”; } // end foreach print “<hr>\n”; } // end while ?> </body> </html> 342 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r . between your PHP program and your MySQL server. You can connect to any server you have permission to use. The mysql_connect function arranges the communication link between MySQL and PHP. Here’s. know how to connect a PHP program to a MySQL database, you’re ready to begin writing the game itself. Connecting to the Adventure Database Once I built the database, the first PHP program I wrote. specified database. Creating a Query Creating a query is very easy. The relevant code from showHero .php is reproduced here: //create a query $sql = “SELECT * FROM hero”; $result = mysql_query($sql,

Ngày đăng: 07/07/2014, 02:20

Mục lục

    PHP 5 / MySQL Programming for the Absolute Beginner

    Chapter 1: Exploring the PHP Environment

    Chapter 2: Using Variables and Input

    Chapter 3: Controlling Your Code with Conditions and Functions

    Chapter 4: Loops and Arrays

    Chapter 5: Better Arrays and String Handling

    Chapter 6: Working with Files

    Chapter 7: Writing Programs with Objects

    Chapter 8: XML and Content Management Systems

    Chapter 9: Using MySQL to Create Databases

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan