Databases Reference
In-Depth Information
The
$ExtraHeaders
string configures who the email appears to be coming from and
where replies to the email will go. If you're using the
error_log( )
function to send
emails, you can pass this same string as an optional fourth parameter.
Modularizing Code
A common requirement in PHP development is to reuse parameters and functions
across many scripts. For example, you might want to use the username and password
credentials many times to connect to the MySQL server, or you might have a function
such as
showerror( )
(described earlier in “Handling MySQL Errors”) that you want to
call from many different places. This section shows you how to do this effectively.
PHP has four built-in functions for including scripts in other scripts. These allow you
to share variables and functions between those scripts without duplicating them, mak-
ing it much easier to maintain code and decreasing the chance of bugs through dupli-
cation and redundancy. The functions are
include( )
,
require( )
,
require_once( )
, and
include_once( )
. We discuss the two
require
variants here, which are identical to the
include
variants in every way, except what happens when an error occurs:
include( )
triggers a PHP
WARNING
(which, by default, doesn't stop the script), while
require( )
triggers a fatal
ERROR
that stops script execution.
Suppose you have the following code that you want to reuse across several scripts:
<?php
$username = "root";
$password = "
the_mysql_root_password
";
$database = "music";
$host = "localhost";
// Custom error handler function
function showerror($connection)
{
die(mysqli_error($connection) . " (" . mysqli_errno($connection) . ")");
}
?>
It's stored in the file
db.php
. You can reuse it with the
require( )
directive. Here's an
example, in which the file
artists.php
reads in and uses the contents of the
db.php
file:
<?php
require "db.php";
// Connect to the MySQL server
if (!($connection = @ mysql_connect($host, $username, $password)))
die("Cannot connect");
if (!(mysql_select_db($database, $connection)))
showerror($connection);
// Run the query on the connection
if (!($result = @ mysql_query("SELECT * FROM artist", $connection)))