96
Chapter 2
...at a glance
PHP
Here’s the script that Frank wrote to take a phone number from the
order form, and look up a customer’s address:
<?php
// Connect to database
$conn = @mysql_connect(“mysql.headrstlabs.com”,
“secret”, “really-secret”);
if (!$conn)
die(“Error connecting to MySQL: “ . mysql_error());
if (!mysql_select_db(“headrst”, $conn))
die(“Error selecting Head First database: “ . mysql_error());
$phone = preg_replace(“/[\. \(\)\-]/”, “”, $_REQUEST[‘phone’]);
$select = ‘SELECT *’;
$from = ‘ FROM hraj_breakneck’;
$where = ‘ WHERE phone = \’’ . $phone’ . ‘\’’;
$queryResult = @mysql_query($select . $from . $where);
if (!$queryResult)
die(‘Error retrieving customer from the database.’);
while ($row = mysql_fetch_array($queryResult)) {
echo $row[‘name’] . “\n” .
$row[‘street1’] . “\n” .
$row[‘city’] . “, “ .
$row[‘state’] . “ “ .
$row[‘zipCode’];
}
mysql_close($conn);
?>
Here’s all the standard
database connection code.
Using the phone
number you sent as
part of the request,
the script looks up the
customer’s address...
...and then echoes the
address back to the
requesting program.
* The version of lookupCustomer.php in the
examples doesn’t use a database, and just returns a
random address, so you don’t need MySQL running
to get Break Neck working on your own computer.
Remember, you don’t need to
understand all this PHP... this is
just for bonus credit.
looking up a customer ...