With SQLite, you
could jump right an and create a database but with
MySQL, you must first connect to the database
server. That is done with the function
mysql_connect(). mysql_connect() has
three required arguments: host, user name and
password; three optional arguments; database name,
port and socket and returns a variable that will
be used in subsquent database interactions or
FALSE if it fails for any reason.
When you use mysql it will look something like
this:
<?
@$connection = mysql_connect("localhost", "user_name", "password") or die("Failure message."); ?>
Note that the function is preceded by an error supression operator. For security reasons, when you finish your scripts, they should reveal as little about the database as possible and a PHP error message may reveal too much. When you are working on the script, you may omit the error supresser but include it when your script is finished and use die to display your own error message when mysql_connect() returns false.
Disconnecting from the database when you are done
with it is not required but it is good form.
Disconnecting from the database is done with the
function mysql_close() which has one
argument; the variable created when you used
mysql_connect(). To close the example above:
<?
mysql_close();
?>
The next example combines the two. The script will
make a connection, tell you if you succeeded (or
filed), then break the connection
<?php
$user = "your user name";
$pass = "your password";
$link = mysql_connect("localhost", "$user", "$pass" );
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysql_connect_error());
exit();
}
else {
printf("Host information: %s\n", mysql_get_host_info($link));
}
/* close connection */
mysql_close($link);
?>
WarningExposing the password to your cPanel is just about the worst thing you can possibly do. Any script you have that can expose source code and accepts a file path may expose your password. If you have such a script, you should either password protect it or modify it so that regular experessions only allows full URL's. If the script is public you may want to create an additional layer of security by storing the username and password as variables on a PHP file in a directory that is not accessable to browsers and including it in your MySQL script. You can't do this if you are using one of the WebTV friendly file managers. You must use cPanel's file manager.
When you use cPanel's file manager, you'll
see a directory named public_html. All
of your public accessible files are in that
directory. None of the contents of any other
directory is accessible to a browser. Create a
directory to put your login script. Make a
login script like this ...
|
<?php |
|
The login script is a function that returns a MySQL resource. Include that file wherever you need to connect to MySQL |
<? |
|
|
|