Current Location: Home> Latest Articles> Complete Guide for PHP to MySQL Connection Setup on Linux

Complete Guide for PHP to MySQL Connection Setup on Linux

gitbox 2025-07-15

Configuring PHP and MySQL Connection on Linux

Connecting PHP to MySQL on a Linux environment is a common task when developing websites and applications. This article provides clear steps and sample code to help you establish the PHP-MySQL connection successfully.

Environment Setup

First, make sure that PHP and MySQL are already installed on your Linux system. You can check if they are installed by running the following commands:

<span class="fun">php -v</span>

If not installed, you can use the package manager to install them. For example, on Ubuntu, you can run the following commands:

<span class="fun">sudo apt update</span>

MySQL Database Setup

Before connecting PHP to MySQL, ensure the MySQL service is running and that you have created the required database and user. Below are commands to create a database and a user:

<span class="fun">CREATE DATABASE your_database_name;</span>

Once done, use FLUSH PRIVILEGES; to apply the permission changes.

PHP Code Example: Using MySQLi to Connect to MySQL

Connecting PHP to MySQL is simple with the MySQLi extension. The following code will establish the connection:

<span class="fun">$servername = "localhost";</span>

Make sure to replace your_username, your_password, and your_database_name with your actual database credentials.

Using PDO to Connect to MySQL

In addition to MySQLi, PHP also supports PDO (PHP Data Objects) for database connections. PDO provides more flexibility for database operations. Below is the PDO connection code example:

<span class="fun">try {</span>

As with the MySQLi example, make sure to replace the relevant details with your actual database information.

Troubleshooting

If you encounter issues while connecting, check the following points:

  • Ensure the MySQL service is running.
  • Verify the username and password are correct.
  • Ensure the database user has sufficient privileges.

Summary

By following this tutorial, you should be able to easily configure PHP to connect to MySQL on a Linux environment. You can use either MySQLi or PDO to achieve database access. In real-world applications, be sure to follow best practices for security and performance. If you run into issues, refer to the official PHP and MySQL documentation for more help.