Connecting to a MySQL Database with PHP Code in cPanel and DirectAdmin Print

  • 0

Introduction: MySQL is a widely-used open-source relational database management system (RDBMS) that enables efficient storage, organization, and management of data. To interact with a MySQL database, you need to establish a connection between your application or website and the database server. In this article, we'll guide you on how to connect to a MySQL database using PHP code in cPanel and DirectAdmin control panels.

 

Here is the Article for : How to connect to the MySQL database

Before you begin, make sure you have the following information:

  1. Hostname: The server's hostname or IP address (found in cPanel or DirectAdmin)
  2. Database Name: The name of the database you want to connect to
  3. Username: The MySQL user with appropriate privileges for the database
  4. Password: The password for the MySQL user
  5. Port: The default MySQL port is 3306 (optional)

Connecting to a MySQL Database Using PHP Code:

Create a new PHP file and include the following code, replacing the placeholders with your actual database connection details:

<?php
// Database connection details
$hostname = 'your_hostname';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database_name';
$port = 3306; // Optional, default MySQL port is 3306

// Create a new connection
$conn = new mysqli($hostname, $username, $password, $database, $port);

// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Save the file with a .php extension (e.g., db_connection.php) and upload it to your server using the File Manager in cPanel or DirectAdmin or an FTP client.

Access the file through your web browser, and if the connection is successful, you'll see the "Connected successfully" message.

Important Security Note: Never store your database connection details directly in your PHP files. Instead, use environment variables, configuration files, or other secure methods to store sensitive information.

Conclusion: Connecting to a MySQL database using PHP code in cPanel and DirectAdmin is a straightforward process. By creating a PHP file with the appropriate code and replacing the placeholders with your actual database connection details, you'll be able to establish a connection and interact with your MySQL database. Remember to follow best security practices when storing and handling sensitive information, such as database credentials, in your PHP files.


Was this answer helpful?

« Back