Database Reference
In-Depth Information
Connecting to the Database
To connect to the database you use the mysql_connect function as follows:
$connectionname = mysql_connect(“server”,“username”,“password”);
$connectionname is a variable that holds the MySQL connection. When you wish to
access this database later on in the script, you will use this variable to reference it.
server is the host name of the server.
username and password are the credentials for accessing the MySQL server. You can see
why it was previously suggested that you have a separate user defined for accessing your
data via the web. You would not want to have to embed your administrator credentials in
every webpage that you created. To quickly set up a user to gain access to MySQL from PHP
on your local machine, open up the MySQLGUI and run the following:
GRANT SELECT
ON mysqlfast.*
TO phpuser@localhost
IDENTIFIED BY “abominable”
This will create a specific user to use PHP and give them access from localhost to the
mysqlfast database. They will have SELECT access only, so will not be able to change any-
thing. This is by far the safest way of granting web access to a database; only give the user
the minimum access to complete the task that they need to perform. You can follow this
command with the or keyword that then allows you to execute code if the command fails.
We won't demonstrate this here but on production pages it is always best to check for error
conditions when you are scripting to make your webpages more resilient.
In our PHP script we can then use the following to connect to the MySQL server:
$myConnection = mysql_connect(“localhost”,“phpuser”,“abominable”);
Selecting the Database
Once you have connected to the server, PHP gives you a command that allows you to select
the data, mysql_select_db . This command is used as follows:
mysql_select_db(“databasename”,connection);
databasename is the name of the database that we will be using. Your user must have
rights to access the database.
connection is the variable that you assigned the connection to in the previous task. If
you are only using one connection you can omit this attribute as PHP will default to the last
connection made.
Sending a Query
With the connection ready, we can now send the query to the connection. PHP uses the
function mysql_query as follows:
Search WWH ::




Custom Search