Databases Reference
In-Depth Information
// ... and print out each of the columns
foreach($row as $data)
print "\t<td>{$data}</td>\n";
// Finish the row
print "</tr>\n";
}
?>
</table>
</body>
</html>
This example uses four key MySQL functions that we'll describe here. Each function
takes one or more arguments and returns a value when it's completed the required
operation. In the list below, we've adhered to convention by writing the return type
first, and then the function name, which is followed by parentheses enclosing the ar-
guments that can be passed to the function:
resource mysql_connect(string
hostname
, string
username
, string
password
)
Opens a connection to the MySQL server. Conceptually, this is the same as running
the MySQL monitor, and it requires the same parameters: a
hostname
that identifies
the server machine, a
username
of a MySQL user, and a
password
for the MySQL
user. The hostname can be an IP address, the mnemonic
localhost
, or a fully
qualified machine and domain, such as
ruttle.invyhome.com
.
By default, a MySQL server listens for incoming connections on port 3306; if your
MySQL server has been configured to use a different port, you can append this to
the hostname as
hostname
:
port
.
If the hostname is
localhost
, PHP makes a fast direct connection through a Unix
socket (under Linux or Mac OS X) or a named pipe (under Windows) rather than
through the network. If your server has been configured with a nonstandard socket
path, you can also append this to the hostname parameter after the port, as in
localhost:
port
:
path_to_socket
. We discussed sockets and named pipes briefly in
“Configuring Access to the MySQL Server” in Chapter 2.
The return value of the function is a
resource handle
that is usually stored in a
variable. The variable is then passed as a parameter to other MySQL functions—
such as
mysql_query( )
—to identify the connection to use. If the function fails, it
returns
false
instead of a connection handle.
Boolean mysql_select_db(string
database
, resource
connection
)
Selects a database to use. This is conceptually identical to typing the
USE
command
in the MySQL monitor. The first parameter is a
database
name to use, and the
second is the MySQL server
connection
to use. The
connection
is the return value
from a previous call to the
mysql_connect( )
function. The function returns
true
on success and
false
on failure.