Monday, October 29, 2007

Connecting to a mySQL database using PHP

SHOW available tables in mySQL database

Similar to opening a file to write to it, you have to open a connection to mySQL before you can do anything. The syntax of this function is as follows:

mysql_connect("localhost OR hostname:port", "httpd OR username", "" or "password");

$mysql_access = mysql_connect("localhost", "username", "password");

The function mysql_close is unnecessary unless you are setting a persistent connection. To set a persistent mySQL connection use:

mysql_pconnect("localhost", "username", "password");

You would want to use persistent connections where you would have a lot of simulataneous connections from the same user through the script.

The following script below will open your mySQL database connection and show the tables available to you in your mySQL database. You must always open a connection to the mySQL database before doing anything else (you only need to open it at the beginning of a script, and then you can run multiple queries if you want). This is good for testing your ability to successfully access the mySQL database.

$mysql_access = mysql_connect("localhost", $user, $pw);
mysql_select_db($db, $mysql_access);

$result = mysql_query("SHOW tables", $mysql_access);
while($row = mysql_fetch_row($result))

in above script

$user is a mysql username.

$pw is mysql password.

$db is mysql database name

No comments: