PHP MySQL tutorial - Connecting to MySQL


Home - Tutorials - Databases

In this PHP MySQL tutorial I will show you how to use basic database manipulation features in PHP.

Tutorial info:


Name:PHP MySQL tutorial
Total steps:5
Category:Databases
Level:Beginner

Bookmark PHP MySQL tutorial



Bookmark and Share

Step 2 - Connecting to MySQL


PHP MySQL tutorial

To use any database in PHP - and in other programming languages as well - you first need to connect to the database server. Connecting to a MySQL database in PHP requires some information. You need to get the following data to establish the connection:

Connecting to a database first you need to connect to the MySQL database server and in the next step you need to select the required database. Of course if the connection to the server failed then it makes no sense to continue the script so we can exit. Let's see how it looks like in PHP: 

Code:
  1. <?php
  2. mysql_connect("localhost", "username", "password") or die(mysql_error());
  3. echo "Connection to the server was successful!<br/>";
  4.  
  5. echo "Database was selected!<br/>";
  6. ?>
  7.  

As you can see the mysql_connect() function establish the connection to the MySQL server and as next step we can select the database with mysql_select_db() function. If you execute the script the output should be the following:
Code:
Connection to the server was successful! Database was selected!

Closing the connection


Before we go on I want to mention the opposite site as well. I mean closing a database connection. From PHP 4 you don't really need to close a database connection opened the way above. This is done automatically by the PHP garbage collector. However it makes no problem if you add the closing statement to your code. You can close a MySQL database connection calling the function mysql_close(). This function closes the actual database connection.





Previous Step of PHP MySQL tutorialNext Step of PHP MySQL tutorial


Tags: php mysql tutorial, php mysql, php database, php, mysql, tutorial



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
CSS F1
Database F1
Flash F1
HTML F1
Java F1
JavaScript F1
PhotoShop F1
PHP F1
Scripts F1
Tutorial F1
Windows F1

Total time: 0.0391