›Type mysql_query to begin the function that sends the query to the MySQL server, and add the query and a variable to store the result identifier.. To use this function, specify the data
Trang 1■ The System variables and
their values are displayed
ˇClick the Home link
to return to the main phpMyAdmin page
ÁClick the Show processes link
■ The MySQL server's current process list is displayed
‡Click the Home link to return to the main phpMyAdmin page
When you select the Users option, the user table in the mysql
database is opened, and the list of current users is displayed The Edit link next to each username allows you to change the user's hostname and assign privileges The Delete link deletes a user The Grants link displays the current list of privileges granted to a user, and allows you
to delete or modify the privileges.
The Users page also includes a form that allows you to create a new user You can specify the hostname the user is allowed to connect from, a password, and the privileges the user should be assigned for
a particular database.
You can also open the mysqldatabase directly in phpMyAdminto work with the various security tables Keep in mind that this feature
is potentially dangerous; if you mistakenly delete the root user, for example, you can lose access to the server See Chapter 11 for more information about managing MySQL security.
For details on using phpMyAdminto manage a MySQL server, see the official documentation The complete phpMyAdmindocumentation is usually installed when you set up this utility To access your local copy
of the documentation, follow the phpMyAdmindocumentation link
on the main page.
227
Trang 2⁄Type <?php to start the
PHP script
Note: You will usually want to include basic HTML tags, as shown here
¤Type mysql_connect( to begin the command
Before you can use any MySQL functions in PHP, you
must first open a connection to the MySQL server.
You can do this using the mysql_connectfunction.
To use this function, specify a hostname, username, and
password for the MySQL server:
$link=mysql_connect("localhost", "testuser",
"testpw");
This command opens a connection to the MySQL server
and returns a link identifier that can be used to perform
operations on the server In this example, the identifier is
stored in the $linkvariable If the connection to the server
is not opened successfully, the boolean value falseis
returned, and an error message is displayed.
If you do not specify one or more of the parameters for the
mysql_connectcommand, PHP assumes default values It
attempts to use localhostas the server hostname, the
username the Web server uses for PHP, and no password If these values do not work on your MySQL server, an error will be returned unless you specify a valid hostname, username, and password.
After you have opened a connection to the MySQL server, you can use the connection throughout the PHP script If you only have a single connection to a single server open, you can use it without needing the link identifier.
The connection to the MySQL server stays open until your PHP script ends, or until you explicitly close the connection.
To close a connection, use the mysql_closecommand and specify the link identifier returned when you opened the connection This command closes the link opened by the previous example:
mysql_close($link);
CONNECT TO A MYSQL SERVER
228
CONNECT TO A MYSQL SERVER
Trang 3‹Add the hostname,
username, and password
for your MySQL server
Note: See Chapter 11 for information
on creating a username and
password
›If desired, add a variable
to store the link identifier returned by mysql_connect
ˇEnd the command with
a closing parenthesis and a semicolon, and press Enter
ÁType ?> to end the script
Note: Add any commands to work with the server before this tag
■ This completes the PHP script to connect to MySQL
MySQL also supports persistent connections This is a special type of
connection that stays open even after the PHP script ends If the same user attempts to connect to the server a second time, PHP finds the existing connection and returns its identifier rather than returning a new connection.
To use persistent connections, use mysql_pconnect()to open the connection The arguments for this function are the same as for the standard mysql_connect()function You cannot close a persistent connection manually; instead, the server will keep the connection open until MySQL's wait_timeoutperiod expires See Chapter 10 for information on setting this timeout value on a MySQL server.
Example:
$link=mysql_pconnect("localhost", "testuser", "testpw");
// Add statements that use the database server here
Persistent connections can be more efficient in an application where the same user will make many queries on different PHP scripts In a simple application, they are less efficient because connections are left open and not used further, and MySQL may run out of connections for future clients.
Persistent connections only work if PHP is running as a module on an Apache Web server They are not currently supported when PHP is run as a CGI program or on other Web servers.
229
Trang 4Note: Start with a basic HTML
document
⁄Type <?php and ?> to
begin and end the PHP script
¤Type mysql_connect
to begin the statement that connects to the database, and add the details for the server, username, and password
‹Type mysql_select_db
followed by the database name to select the database for future queries
›Type mysql_query to begin the function that sends the query to the MySQL server, and add the query and a variable to store the result identifier
After you have connected to the MySQL server from a
PHP script, you can run one or more MySQL queries.
Often, you will want to send a SELECTquery to the
server and display the resulting data PHP includes a
number of ways to receive data from the SQL server.
As with the MySQL monitor, before you can make a query,
you must select a database To do this, use the mysql_
select_dbfunction To use this function, specify the
database name as a string:
mysql_select_db("testdb");
After you have selected a database, you can send an SQL
query to the server using the mysql_queryfunction To
use this function, specify the query as a string The following
example sends a simple SELECTquery to the server:
$result=mysql_query("SELECT quote, author
FROM quotes");
If the query is successful, the mysql_queryfunction
returns a result identifier In this example, the $result
variable stores the result identifier You can use this
identifier later in the script to display the query results.
While the result identifier indicates that the query was successful, this only means that MySQL understood the query — it does not mean there are definitely one or more rows of data in the result If the query is unsuccessful, the
mysql_queryfunction returns a FALSEvalue instead Some queries, such as INSERTand DELETE, do not return data from the server In this case,mysql_querysimply returns TRUEif the query was successful.
To display query results, you can use the mysql_fetch_row
function This function accepts a result identifier, and returns the next row of the result as an array The array includes all of the columns of the result in order You can repeat the function to retrieve all of the result rows The following example uses a whileloop to retrieve all of the rows:
while(list($quote, $author) = mysql_fetch_row($result)) { echo "<p>$quote $author</p>"; }
This example retrieves each row into the $quoteand
$authorvariables These are used with an echostatement
to display each row as an HTML paragraph The list
function allows the array returned by mysql_fetch_row
to be stored in two regular variables instead of an array, and
is a convenient way to handle simple queries.
DISPLAY QUERY RESULTS
230
DISPLAY QUERY RESULTS
Trang 5ˇType while to begin
the loop, and add the
mysql_fetch_row
statement Include braces
to enclose the loop
ÁType echo to begin the statement that displays each row Add the string to display and a closing bracket to end the loop
‡Load your PHP document into a Web browser
■ The rows of data are displayed within the HTML document
Note: This example uses the quotes table in the testdb database You can import this table from the CD-ROM
You can optionally specify a link identifier from mysql_connectas
a second parameter to the mysql_select_dband mysql_query
functions However, these and most other MySQL functions in PHP default to using the last connection you opened, so this is usually not necessary.
You can use the mysql_db_queryfunction to avoid selecting a database first This function is similar to mysql_query, but accepts a database name as its first parameter.
To use this script or any PHP script you create, you must first save the edited file, and then upload it to your Web server that supports PHP.
If you are using PHP version 3, save the file with the php3 extension.
For PHP version 4, save the file with the php extension.
After the file is saved, you will need to upload it to the correct directory of the Web server You can do this using the same program you use to upload HTML documents Typically this is done using the FTP protocol.
After the file is uploaded to the server, you can use a Web browser to display the result PHP does not require a particular browser because
it creates HTML output PHP pages display just like HTML pages.
231
Trang 6Note: Start with a basic HTML
document
⁄Type <?php and ?> to
begin and end the PHP script
¤Type mysql_connect
followed by the correct user, password, and hostname to connect to the database
‹Type mysql_select_db
followed by the database name to select the database for future queries
›Type $result = mysql_query
to begin the function that sends the query to the MySQL server, and add the query in quotation marks Note: This example uses the quotes table in the testdb database You can import this table from the CD-ROM
When you use the mysql_fetch_rowfunction to
retrieve rows from a query, you must specify the column names in the query and retrieve them in the same order If you are trying to use a query that returns
all columns of a table, and are unsure of the order the
columns will be returned in, you can use mysql_fetch_
objectinstead.
For example, suppose you have made the following query
to the MySQL server This query retrieves all columns and
all rows from the quotes table.
$result=mysql_query("SELECT * FROM quotes");
To retrieve the data, you can use mysql_fetch_object.
This returns an object whose properties are the column
values for the row Thus, you can refer directly to the
MySQL column names rather than assigning your own
variable names to each column The following whileloop
uses the mysql_fetch_objectfunction to retrieve and
display each row:
while($row = mysql_fetch_object($result)) { echo "<p>$row->quote $row->author</p>"; }
In this example, the $rowvariable stores each row You can use the ->operator to refer to each MySQL column name
as a property of the object Thus, you can refer to the quote column as $row->quoteand the author column as
$row->author Because the MySQL query specified the wildcard
*rather than specific column names, all columns of the table are available from the object.
You can use whichever function you are most comfortable with to return data from a MySQL query The data returned
is the same; only the method you use to access it changes PHP includes several other fetchcommands that return the results in different formats, such as mysql_fetch_assoc
to store the data in an associative array This type of array uses column names to index the results rather than numeric indexes.
STORE QUERY RESULTS AS OBJECTS
232
STORE QUERY RESULTS AS OBJECTS
Trang 7ˇType while to begin the
loop that iterates through
the rows of data Add the
statement to retrieve a row
and an opening brace to
begin the loop
ÁType echo followed by a string using the $row object
to display the row Add the closing brace to end the loop
‡Load your PHP document into a Web browser
■ The rows of data are displayed within the HTML document
If you are running into MySQL errors while attempting to use a database from PHP, it is useful to display the results within your PHP script The following PHP script adds ifstatements to check whether each MySQL command succeeded It displays an appropriate error message if any command fails.
Example:
<?php
$link = mysql_connect("localhost", "testuser", "testpw");
if (!$link) echo "Failed to connect to MySQL server!";
$status=mysql_select_db("testdb");
if (!$status) echo "Failed to select database!";
$result=mysql_query("SELECT * FROM quotes");
if (!$result) echo "The MySQL query failed!";
while($row = mysql_fetch_object($result)) { echo "<p>$row->quote $row->author</p>"; }
?>
This example checks the results of the mysql_connect,mysql_select_db,
mysql_query, and mysql_fetch_objectcommands All of these return a
FALSEvalue if they fail The one condition that these do not account for is if the query succeeds but returns a zero-row result If this happens, the while
loop will end immediately without displaying any data.
233
Trang 8Note: Start with a basic HTML
document
⁄Type <?php and ?> to
begin and end the PHP script
¤Type mysql_connect
followed by the username, host, and password to connect
to the MySQL server
‹Type mysql_select_db
followed by the database name to select the database
Note: This example uses the testdb database and the scores table You can import this table from the CD-ROM
›Type $query= followed
by the MySQL query in quotation marks
ˇType $success = mysql_query ($query); to create the statement that sends the query to the server
You can use the mysql_querycommand in PHP to
send an INSERTquery to the MySQL server When
you do this, a result identifier is not returned because
an INSERTquery does not return any data from the MySQL
server Instead, the result returned from mysql_queryis a
simple trueor falsevalue that indicates whether the
query was successful.
For example, the following PHP statements add a record to
the scores table and display a message indicating success or
failure:
$query="INSERT INTO scores (name, score)
VALUES ('Fred', 92)";
$success = mysql_query($query);
if ($success) echo "The INSERT query was
successful.";
else echo "Error: INSERT query failed.";
This example stores the query in the $queryvariable, and
then uses the mysql_queryfunction to send the query to
the MySQL server The result of the query is stored in the
$successvariable The ifstatement checks this variable and displays a success message, and the elsestatement displays an error message if the insert was unsuccessful Unlike SELECTqueries, an INSERTquery does not return a result identifier The result stored in the $successvariable will be a simple TRUEor FALSEvalue.
As with other MySQL queries, you must first connect to the MySQL server using the mysql_connectfunction, and then select a database with mysql_select_dbbefore attempting to insert a row You must be connected using a MySQL username that has the INSERTprivilege for the table you are using in the INSERTcommand.
Because double quotation marks are used to define the
$querystring, you cannot use double quotes inside the query You can substitute single quotation marks within the query Only values to be stored in text columns need to be quoted You can use a PHP variable within the INSERT
query by including its name in the $querystring.
INSERT A RECORD FROM PHP
234
INSERT A RECORD FROM PHP
Trang 9ÁType if to begin the
statement that checks whether
the query succeeded, followed
by echo and the success
message in quotation marks
‡Type else to begin the statement that checks for an error, and type echo followed
by the error message
°Load the PHP document into a Web browser
■ The displayed message indicates whether the INSERT query was successful
If a table includes an auto-increment column, it will automatically be updated with a new unique value each time you insert a record After you have inserted a row into a table from PHP, you can use the mysql_insert_idfunction to find out what number was assigned to the auto-increment field in the INSERTquery.
This technique is useful because you now have a value that you can use to find the inserted row in a subsequent query Without this feature, you would have to use a separate query to find the newest row, and even that may find a row inserted by a different user.
For example, the following PHP code inserts a row into the quotes table and then displays the ID assigned to the auto-increment field.
Example:
$link=mysql_connect("localhost", "testuser", "testpw");
mysql_select_db("testdb");
$query = "INSERT INTO quotes (quote, author) VALUES ";
$query = "('Union gives strength.', 'Aesop')";
$success = mysql_query($query);
if ($success) { echo "The INSERT query was successful.";
echo "The record number is: " + mysql_insert_id();
} else echo "Error: INSERT query failed.";
You can optionally specify a link identifier from mysql_connectwith the mysql_insert_id
function If you do not use an identifier, the most recent connection used is assumed.
235
Trang 10Note: Start with a basic HTML
document
Note: This example uses the scores
table in the testdb database
⁄Type <?php and ?> to
begin and end the PHP script
¤Type mysql_connect
followed by the username, password, and hostname to connect to the MySQL server
‹Type mysql_select_db
followed by the database name to select the database
›Type $query= followed by the DELETE query
ˇType $success=mysql_ query($query); to send the query to the server
You can also use PHP to send a DELETEquery to the
MySQL server As with an INSERTquery, when you
use the mysql_queryfunction with a DELETE
query, a simple trueor falseresult is returned that
indicates whether the delete was successful.
To delete one or more rows of a table, you usually will need
to specify a WHEREclause Without this clause, all records of
the table would be deleted The following PHP statements
send a DELETEquery to the MySQL server:
$query="DELETE FROM scores WHERE name =
'fred'";
$success=mysql_query($query);
if ($success) echo "The DELETE query was
successful.";
else echo "Error: DELETE query failed.";
These statements store the query in the $queryvariable and send it to the MySQL server using the mysql_query
function The ifstatement displays a message if the
DELETEquery succeeded, and the elsestatement displays
a message if the query failed.
Note that a failed query is not the same as a nonmatching
WHEREclause If the WHEREclause does not match any records, the mysql_queryfunction will still succeed The query will only fail if the server cannot be reached, or if there is a syntax error in the query.
You can find out how many rows were affected by the
DELETEquery with the mysql_affected_rowsfunction This function returns the number of rows affected by the most recent DELETE,INSERT, or UPDATEquery You can use this to determine how many rows the WHEREclause matched.
DELETE RECORDS USING PHP
236
DELETE RECORDS USING PHP