5.4. Selecting a Database

If you don't select the database in the connect function, you can select the database by using the mysqli_select_db function. You can also use this function to select a different database at any time in your script. The format is

mysqli_select_db($cxn,"databasename")
      or die ("message");

If you're using the mysql functions, rather than the mysqli functions, you must select the database in a separate function, using mysql_select_db. The section "Converting mysqli Functions to mysql Functions," later in this chapter, explains in more detail.

Fill in the following information:

  • cxn: The variable that contains the connection information.

  • databasename: The name of the database.

  • message: The message that's sent to the browser if the database can't be selected. The selection might fail because the database can't be found, which is usually the result of a typo in the database name.

For instance, you can select the database Customer with the following statement:

mysqli_select_db($cxn,"Customer")
      or die ("Couldn't select database.");

If mysqli_select_db can't select the database, the script stops running and the message Couldn't select database. is sent to the browser.

The database stays selected until you select a different database. To select a different database, just use a new mysqli_select_db function statement.

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® 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.