Chapter 15. Integrating PHP and MySQL
After you've installed and set up your MySQL database, you can begin to write PHP scripts that interact with it. Here, we will try to explain all the basic functions that enable you to pass data back and forth from web site to database.
Note
Information related to creating a MySQL database is at the end of this chapter, because it is a more advanced skill that builds on the fundamental MySQL skills discussed in the earlier parts of the chapter.
Connecting to MySQL
The basic command to initiate a MySQL connection is
mysql_connect($hostname, $user, $password);
if you're using variables, or
mysql_connect('localhost', 'root', 'sesame');
if you're using literal strings.
The password is optional, depending on whether this particular database user requires one (it's a good idea). If not, just leave that variable off. You can also specify a port and socket for the server ($hostname:port:socket
), but unless you've specifically chosen a nonstandard port and socket, there's little to gain by doing so.
The corresponding mysqli
function is mysqli_connect
, which adds a fourth parameter allowing you to select a database in the same function you use to connect. The function mysqli_select_db
exists, but you'll need it only if you want to use multiple databases on the same connection.
You do not need to establish a new ...
Get PHP6 and MySQL® 6 Bible now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.