Getting a Connection The first job is to get a connection between your PHP program and your MySQL server.. You will probably have to change the username and password fields if you are ru
Trang 1g r
s o
l u
g in
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
$conn = mysql_connect(“localhost”, “”, “”);
• Server name The server name is the name or URL of the MySQL server you
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
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
T R A P
H I N T
Trang 2Choosing a Database
A data connection can have a number of databases connected to it The
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
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!)
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
query, the result variable holds a pointer to the data, which is taken apart in the
T R A P
339
i t
I N THE R EAL W ORLD 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.
Trang 3g r
s o
l u
g in
e r
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”;
in the result, the function returns the value FALSE This allows the field function
to also be used as a conditional statement
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
T A B L E 1 0 1 C O M M O N L Y U S E D F I E L D
O B J E C T P R O P E R T I E S
Trang 4By 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
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
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.
(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
H I N T
341
i t
Trang 5Once you’ve gotten a row, it’s stored as an associative array You can manipulate
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
g r
s o
l u
g in
e r