- PHP mysqli connect() Function
- Syntax
- Object oriented style:
- Procedural style:
- Parameter Values
- Technical Details
- Example — Procedural style
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- How to Connect to MySQL Using PHP
- 2 Ways to Connect to MySQL database using PHP
- Option 1: Connect to MySQL with MySQL Improved extension
- Credentials Explained
- Option 2: Connect To MySQL With PDO
- Credentials Syntax
- Try and Catch Blocks
- Potential Errors with MySQLi and PDO
- Incorrect Password
- Unable to Connect to MySQL Server
- Php mysql connect inc php
- MySQL’s PHP Connector
PHP mysqli connect() Function
The connect() / mysqli_connect() function opens a new connection to the MySQL server.
Syntax
Object oriented style:
Procedural style:
Parameter Values
Parameter | Description |
---|---|
host | Optional. Specifies a host name or an IP address |
username | Optional. Specifies the MySQL username |
password | Optional. Specifies the MySQL password |
dbname | Optional. Specifies the default database to be used |
port | Optional. Specifies the port number to attempt to connect to the MySQL server |
socket | Optional. Specifies the socket or named pipe to be used |
Technical Details
Example — Procedural style
Open a new connection to the MySQL server:
// Check connection
if (mysqli_connect_errno()) echo «Failed to connect to MySQL: » . mysqli_connect_error();
exit();
>
?>
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
How to Connect to MySQL Using PHP
To access and add content to a MySQL database, you must first establish a connection between the database and a PHP script.
In this tutorial, learn how to use MySQLi Extension and PHP Data Objects to connect to MySQL. Traditional legacy mysql_ functions are deprecated and we will not cover them in this guide.
2 Ways to Connect to MySQL database using PHP
There are two popular ways to connect to a MySQL database using PHP:
The guide also includes explanations for the credentials used in the PHP scripts and potential errors you may come across using MySQLi and PDO.
Option 1: Connect to MySQL with MySQL Improved extension
MySQLi is an extension that only supports MySQL databases. It allows access to new functionalities found in MySQL systems (version 4.1. and above), providing both an object-oriented and procedural interface. It supports server-side prepared statements, but not client-side prepared statements.
The MySQLi extension is included PHP version 5 and newer.
The PHP script for connecting to a MySQL database using the MySQLi procedural approach is the following:
connect_error) < die("Connection failed: " . $conn->connect_error); > echo “Connected successfully”; mysqli_close($conn); ?>
Credentials Explained
The first part of the script is four variables (server name, database, username, and password) and their respective values. These values should correspond to your connection details.
Next is the main PHP function mysqli_connect(). It establishes a connection with the specified database.
Following is an “if statement.” It is the part of the code that shows whether the connection was established. When the connection fails, it gives the message Connection failed. The die function prints the message and then exits out of the script.
If the connection is successful, it displays “Connected successfully.”
When the script ends, the connection with the database also closes. If you want to end the code manually, use the mysqli_close function.
Option 2: Connect To MySQL With PDO
PHP Data Objects (PDO) is an extension that serves as an interface for connecting to databases. Unlike MySQLi, it can perform any database functions and is not limited to MySQL. It allows flexibility among databases and is more general than MySQL. PDO supports both server and client-side prepared statements.
Note: PDO will not run on PHP versions older than 5.0 and is included in PHP 5.1.
The PHP code for connecting to a MySQL database through the PDO extension is:
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo “Connection Okay”; return $pdo > catch (PDOException $e) < echo “Connection failed: ”. $e->getMessage(); > ?>
Credentials Syntax
First, we have five variables (server name, database, username, password, and charset) and their values. These values should correspond to your connection details.
The server name will be localhost. If connected to an online server, type in the server name of that server.
The variable charset tells the database in which encoding it will be receiving and sending data. The recommended standard is utf8mb4.
Try and Catch Blocks
PDO’s great asset is that it has an exception class to take care of any potential problems in database queries. It solves these problems by incorporating try and catch blocks.
If a problem arises while trying to connect, it stops running and attempts to catch and solve the issue. Catch blocks can be set to show error messages or run an alternative code.
The first parameter in the try and catch block is DSN, which stands for data(base) source name. It is crucial as it defines the type and name of the database, along with any other additional information.
In this example, we are using a MySQL database. However, PDO supports various types of databases. If you have a different database, replace that part of the syntax (mysql) with the database you are using.
Next is the PDO variable. This variable is going to establish a connection to the database. It has three parameters:
- The data source name (dsn)
- The username for your database
- The password for your database
Following is the setAttribute method adding two parameters to the PDO:
This method instructs the PDO to run an exception in case a query fails.
Add the echo “Connection Okay.” to confirm a connection is established.
Return the PDO variable to connect to the database.
After returning the PDO variable, define the PDOException in the catch block by instructing it to display a message when the connection fails.
Potential Errors with MySQLi and PDO
Incorrect Password
The password in the PHP code needs to correspond with the one in the database. If the two do not match, a connection with the database cannot be established. You will receive an error message saying the connection has failed.
Possible solutions:
- Check the database details to ensure the password is correct.
- Ensure there is a user assigned to the database.
Unable to Connect to MySQL Server
PHP may not be able to connect to the MySQL server if the server name is not recognized. Make sure that the server name is set to localhost.
In case of other errors, make sure to consult the error_log file to help when trying to solve any issues. The file is located in the same folder where the script is running.
This guide detailed two ways to connect to a MySQL database using PHP.
Both MySQLi and PDO have their advantages. However, bear in mind that MySQLi is only used for MySQL databases. Therefore, if you want to change to another database, you will have to rewrite the entire code. On the other hand, PDO works with 12 different databases, which makes the migration much easier.
Php mysql connect inc php
The first step when dealing with MySQLconnecting to the serverrequires the appropriately named mysqli_connect() function:
$database_connection = mysqli_connect ( 'host', 'user', 'password' );
The values you use in place of host , user , and password are determined from the users and privileges set up within the mysql database (see Chapter 2, «Running MySQL,» for more information). Normally, the host will be localhost , but not necessarily. In any case, the most important rule about connecting to MySQL from PHP is this: use the same username/hostname/password combination that you would to connect using the mysql client.
The $database_connection variable is a reference point that PHP will use to the newly created connection (you can use another name for this variable, like just $dbc). Many of the other PHP functions for interacting with MySQL will take this variable as an argument.
Once you have connected to MySQL, you will need to select the database with which you want to work. This is the equivalent of saying USE databasename within the mysql client and is accomplished with the mysqli_select_db() function:
mysqli_select_db($dbc, "databasename" );
Alternatively, you can connect to MySQL and select the database in one fell swoop:
$dbc = mysqli_connect ( "host", "user", "password", "databasename" );
I’ll start the demonstration of connecting to MySQL by creating a special file just for that purpose. Every PHP script that requires a MySQL connection can then include this file.
MySQL’s PHP Connector
Because PHP and MySQL go so well together, the good people at MySQL provide updated versions of the mysql and mysqli libraries for PHP. The connector package is just a build of the MySQLrelated PHP functions, but using the latest versions of the MySQL client libraries (which PHP itself may or may not contain).
The connector will contain all bug fixes and support the latest MySQL features. You can download the latest connector package from the MySQL Web site. Note that it is only available for Windows and that installation instructions are included on the connector’s download page.
To connect to and select a database:
Begin a new PHP document in your text editor (Script 7.1).
Add the appropriate comments.
// ***** mysql_connect.inc.php ***** // ***** Script 7.1 ***** // Developed by Larry E. Ullman // MySQL: Visual QuickStart Guide // SECOND EDITION // Contact: mysql2@DMCinsights.com // Created: February 15, 2006 // Last modified: February 15, 2006 // This file contains the database access information // for the accounting database. // This file also establishes a connection to MySQL // and selects the accounting database.
For the most part, I will refrain from including prodigious comments within the steps, but I did want to pinpoint these lines to give you a sense of how I might document a configuration file. Also, as a matter of convenience, I’ll include the filename and script name as a comment in every script in this book (for easier reference).
Script 7.1. The mysqli_connect.inc.php script will be used by every other script in this application. In this script, a connection to the database is established.
Set the database host, username, password, and database name as constants.
DEFINE (`DB_USER', `username'); DEFINE (`DB_PASSWORD', `password'); DEFINE (`DB_HOST', `localhost'); DEFINE (`DB_NAME', `accounting');
I prefer to establish these variables as constants for security reasons (they cannot be changed this way), but that isn’t required. Setting these values as some sort of variable makes sense so that you can separate the configuration parameters from the functions that use them, but again, this is not required.
The only truly important consideration is that you use a username/hostname/password combination that has privileges in MySQL to interact with the accounting database.
Connect to MySQL and select the database to be used.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
The mysqli_connect() function, if it successfully connects to MySQL, will return a resource link that corresponds to the open connection. This link will be assigned to the $dbc variable.
While connecting, I’m also selecting the database (since this application will interact with only one database). Failure to select the database will create problems in later scripts, although if an application uses multiple databases, you might not want to globally select one here.
Close the PHP and save the file as
I chose to name the file with an .inc.php extension. This indicates to me that the file is used as an inclusion in other PHP scripts.
Upload the file to your server, above the Web document root (Figures 7.1 and 7.2).
Figure 7.1. Assuming that html is the root directory of my Web documents (e.g., www.dmcinsights.com or http://localhost would lead there), the configuration files should be stored outside of it. This image was taken on Mac OS X.
Figure 7.2. Assuming that wwwroot is the root directory of my Web documents (e.g., www.dmcinsights.com or http://localhost would lead there), the configuration files should be stored outside of it. This image was taken on Windows.
Because the file contains sensitive MySQL access information, it ought to be stored securely. If you can, place it in the directory immediately above or otherwise outside of the Web directory. This isn’t required, but it’s a nice bit of extra security.
Tips
- If you place the connection script in the Web directory, then you can run it in a Web browser. If there are no problems , the result will be a blank page. If a connection problem occurs, you’ll see error messages.
- In this Chapter I discuss the most important of PHP’s mysqli functions. All of these, and many, many more, are well documented in the PHP manual ( not the MySQL manual). You’ll also find plenty of sample usage code there.
- Once you’ve written one mysqli_connect.inc.php file, you can easily make changes to the DEFINE() lines to use the script for other projects.