Connect to a MySQL database
By: Daniel

Leaning to work with databases in your PHP starts with understanding on how to connect to the server with PHP. Using only a few lines of code you can easily connect to a database.

<?php
define('SQL_SERVER', 'localhost'); // Specify the server address for the MySQL server, localhost is standard
define('SQL_USERNAME', 'root'); // Specify server username, replace root with your username
define('SQL_PASSWORD', 'password'); // Specify the server password, replace password with your password
define('SQL_DATABASE', 'testing'); // Specify the database name, replace testing with your database name

// Attempt to connect to the server using the constants(variables) specified above
$db = @mysql_connect(SQL_SERVER, SQL_USERNAME, SQL_PASSWORD) or die('Could not connect to the database server');
// Now try connecting to the database in SQL_DATABASE
$link = @mysql_select_db(SQL_DATABASE, $db) or die('Could not connect to the database name specified');
?>

In the code above, I have used define() function to create variables of the MySQL server, username, password and database name. I then use these variables in the next lines of code that actually connects to the server.

There are two types of error handling here in this piece of code. The first is the @, placing this before a function hides any kind of error messages that the two functions could display. The second part is the or die() addition at the end of each connect function. Putting this here stops the rest of the code from being executed and shown to the client.

If when you execute this code it does not show any errors, you are then connected to your database server and can use the mysql_query() function or any other mysql function to manipulate your database.

1 Votes | Average: 5 out of 51 Votes | Average: 5 out of 51 Votes | Average: 5 out of 51 Votes | Average: 5 out of 51 Votes | Average: 5 out of 5 (1 votes, average: 5 out of 5)
Loading ... Loading ...
del.icio.us:Connect to a MySQL database digg:Connect to a MySQL database spurl:Connect to a MySQL database wists:Connect to a MySQL database simpy:Connect to a MySQL database newsvine:Connect to a MySQL database blinklist:Connect to a MySQL database furl:Connect to a MySQL database reddit:Connect to a MySQL database fark:Connect to a MySQL database blogmarks:Connect to a MySQL database Y!:Connect to a MySQL database smarking:Connect to a MySQL database magnolia:Connect to a MySQL database segnalo:Connect to a MySQL database

Leave a Reply

eXTReMe Tracker
geovisitors