How to Connect to the MySQL Server with the PHP mysql_connect Function

How to Connect to the MySQL Server with the PHP mysql_connect Function
When you are ready to work with the MySQL database in your PHP programs, the first thing you must do is connect to (or identify yourself to) the MySQL server. Here is the PHP function you will use to open a connection to the MySQL server.

$connection =
mysql_connect("host", "username", "password");
Note--The arrow indicates that the code is wrapped to a second line and should really be all on one line.

This simple line of code is all you need to identify yourself, and your program, to the MySQL server. The variable $connection is the name I have given for this variable. Of course, you can use any name you prefer. You will want to replace the host name with the name that your hosting company instructs you to use here. Most of the time, it will be localhost. Check their online documentation or user's manual. You will also need to replace the username and password with the username and password given to you by your hosting company. You will probably find this in the welcome email sent to you when you opened your account.

If the server is not available for some reason, an error message such as the one below will be sent to the web browser.

Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on 'localhost' (10061) in C:\sokkit\site\test.php3 on line 4

You may not want your site visitors to see this technical error message. In that case, you can prevent the error message by placing an @ in front of the mysql_connect().

$connection =
@mysql_connect("host", "username", "password");
Note--The arrow indicates that the code is wrapped to a second line and should really be all on one line.

You may want to send a nice message to your site visitors telling them to try again later. You can use the die statement for this.

$connection =
@mysql_connect("host", "username", "password")
or die ("Could not connect to the database server
at this time. Please try later.");
Note--The arrow indicates that the code is wrapped to a second line and should really be all on one line.

If the MySQL server is unavailable, the text string you place between the quotation marks will be sent to the browser.






This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.