Current Location: Home> Latest Articles> A Detailed Guide to PHP Connecting to MySQL Database on CentOS

A Detailed Guide to PHP Connecting to MySQL Database on CentOS

gitbox 2025-07-01

Environment Setup

Before starting, make sure your CentOS system has Apache and PHP installed. If not, use the following command to install them:

<span class="fun">sudo yum install httpd php php-mysqlnd</span>

Install MySQL

Next, install the MySQL database. If you haven't installed it yet, use this command:

<span class="fun">sudo yum install mysql-server</span>

After installation, start the MySQL service and set it to start on boot:

<span class="fun">sudo systemctl start mysqld</span>
<span class="fun">sudo systemctl enable mysqld</span>

Configure MySQL Database

When MySQL is started for the first time, it generates a temporary password. You can view this password using the following command:

<span class="fun">sudo grep 'temporary password' /var/log/mysqld.log</span>

Use this temporary password to log in to MySQL and change it to a more secure one:

<span class="fun">mysql -u root -p</span>

Once logged in, execute the following commands to create a new database and user:

<span class="fun">CREATE DATABASE my_database;</span>
<span class="fun">CREATE USER 'my_user'@'localhost' IDENTIFIED BY 'my_password';</span>
<span class="fun">GRANT ALL PRIVILEGES ON my_database.* TO 'my_user'@'localhost';</span>

PHP Script to Connect to MySQL

<span class="fun">$servername = 'localhost';</span>
<span class="fun">$username = 'my_user';</span>
<span class="fun">$password = 'my_password';</span>
<span class="fun">$dbname = 'my_database';</span>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

echo 'Connection successful';
$conn->close();

Error Handling

In real-world applications, it's important to handle connection errors. The example above includes basic error handling, where the system returns the relevant error message if the connection fails.

Conclusion

Connecting PHP to MySQL on CentOS is not complicated. With this tutorial, you can understand the entire process from environment setup to the actual connection, and implement appropriate security measures in a production environment to ensure data safety.