Databases Reference
In-Depth Information
print "<tr>\n";
// ... 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>
The example uses three key MySQLi functions, described next in a simplified form. As
with the standard MySQL library, each function takes one or more arguments and
returns a value when it's completed the required operation. Again, we follow conven-
tion and write the return type first, then the function name, and, in parentheses, the
list of arguments that can be passed to the function:
resource mysqli_connect(string
hostname
, string
username
, string
password
,
string
database
)
Opens a connection to the MySQL server and uses a database. Conceptually, this
is the same as running the MySQL monitor and issuing a
USE
command. It requires
the same parameters and input: a
hostname
that identifies the server machine, a
username
of a MySQL user, a
password
for the MySQL user, and the
database
to
use. The hostname can be an IP address, the mnemonic
localhost
, or a fully quali-
fied 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 specify this as
an additional parameter to
mysqli_connect( )
after the
database
name. If the host-
name 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 as an additional parameter after the port. 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 passed as a parameter to other MySQL functions—such
as
mysqli_query( )
—to identify the connection to use. If the function fails, it re-
turns
false
instead of a connection handle.
The database is selected when the connection is established. You can change the
active database using the
mysqli_select_db( )
function, but you normally just use
the database that you activated in the call to
mysqli_connect( )
.