How to Select a MySQL Database

by austingulati on January 20, 2011

  • Share
  • CevherShare
  • Share

Before you get your code up and running, you have to do a few things. One of the things that you will have to do is select the MySQL database.

The reason that you have to select the database is that the script has to know which database to use. Within the whole MySQL server, there can be as many databases as resources allow. The database that you are using has to be specified, other your queries will not run.

The syntax to select the MySQL database is as follows:

mysql_select_db ($database_name , [$link_identifier])

The first parameter is fairly self explanatory. The second one is the link identifier returned by the mysql_connect function that you had to have used before calling this function. You don’t have to pass this second parameter – the last created link is used automatically if this is not included.

The function returns true if the link was successfully created, otherwise false.

It’s also possible to work around this if you need to make queries to multiple databases in a short amount of time. You can specify the database that a table resides under in the query itself, like so:

SELECT * FROM database_name.table_name

It’s much easier to just select the MySQL database if you are using the same database every time, though. Especially if it’s possible that the name of the database would change, since that would force you to change the name in all of the places that it appeared directly in queries.

If you have any questions about selecting databases, please leave a comment!

Leave a Comment

Previous post:

Next post: