In modern website development, the choice of database is crucial. MariaDB, known for its high performance and open-source nature, has become the preferred choice for many developers. PHP, as a powerful tool for dynamic website development, works seamlessly with MariaDB. This guide will provide a detailed explanation of how to use PHP to connect to MariaDB in a Linux environment and help you set up the backend database for your website.
Before you begin, ensure that MariaDB and PHP are already installed on your Linux system. You can install the required software using the following commands:
sudo apt-get update
sudo apt-get install mariadb-server php php-mysql
After installation, you need to perform the initial configuration for MariaDB, including setting a root password and creating a new database. Use the following command to access the MariaDB terminal:
<span class="fun">sudo mysql</span>
In the MariaDB terminal, run the following command to set the root user password:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'your-strong-password';
FLUSH PRIVILEGES;
Next, create a new database. For example, you can create a database called test_db:
<span class="fun">CREATE DATABASE test_db;</span>
Before connecting to the database, make sure your PHP environment is running properly. Next, create a new PHP file, such as connect.php, and add the following code:
$servername = 'localhost';
$username = 'root';
$password = 'your-strong-password';
$dbname = 'test_db';
<p>// Create connection<br>
$conn = new mysqli($servername, $username, $password, $dbname);</p>
<p data-is-last-node="" data-is-only-node="">// Check connection<br>
if ($conn->connect_error) {<br>
die('Connection failed: ' . $conn->connect_error);<br>
}<br>
echo 'Connection successful';<br>
$conn->close();
Upload the connect.php file to your server and access the file through your browser. If all configurations are correct, you will see a “Connection successful” message, indicating that PHP has successfully connected to the MariaDB database.
If the connection fails, common causes may include:
With this guide, you should be able to successfully connect to MariaDB using PHP in a Linux environment. Whether you are building personal projects or enterprise-level applications, the combination of PHP and MariaDB offers excellent performance and flexibility. We hope this guide helps you with your website development!