62
271
Setting Up a Connection
Here, you use the function
htmlspecialchars()
to encode characters that have spe-
cial meanings in HTML.The current test data does not include any ampersands (
&
),less
than (
<
),greater than (
>
),or double quotation mark (
“
) symbols,but many fine book
titles contain an ampersand.By using this function,you can eliminate future errors.
Setting Up a Connection
PHP5 has a new library for connecting to MySQL.This library is called mysqli (the i
stands for improved).The mysqli library is suitable for use with MySQL version 4 and
later.At version 4,a new connection protocol that is much faster was added to MySQL,
and mysqli allows you to take advantage of it.The mysqli library allows you to use either
an object-oriented or procedural syntax.
You use the following line in the script to connect to the MySQL server:
@ $db = new mysqli(‘localhost’, ‘bookorama’, ‘bookorama123’, ‘books’);
This line instantiates the
mysqli
class and creates a connection to host
‘localhost’
with username
‘bookorama’
,and password
‘bookorama123’
.The connection is set up
to use the database called books.
Using this object-oriented approach,you can now invoke methods on this object to
access the database.If you prefer a procedural approach,mysqli allows for this,too.To
connect in a procedural fashion,you would use
@ $db = mysqli_connect(‘localhost’, ‘bookorama’, ‘bookorama123’, ‘books’);
This function returns a resource rather than an object.This resource represents the con-
nection to the database, and if you are using the procedural approach, you will need to
pass this resource in to all the other mysqli functions.This is very similar to the way the
file-handling functions,such as
fopen()
,work.
Most of the mysqli functions have an object-oriented interface and a procedural
interface.Generally,the differences are that the procedural version function names start
with
mysqli_
and require you to pass in the resource handle you obtained from
mysqli_connect()
.Database connections are an exception to this rule because they can
be made by the mysqli object’s constructor.
The result of your attempt at connection is worth checking because none of the rest of
code will work without a valid database connection.You do this using the following code:
if (mysqli_connect_errno())
{
echo ‘Error: Could not connect to database. Please try again later.’;
exit;
}
(This code is the same for the object-oriented and procedural versions.) The
mysqli_connect_errno()
function returns an error number on error,or zero on success.