Connecting to MySQL with PHP: A Simple Guide

AvaHost’s hosting platform, powered by NVMe SSDs, offers robust PHP and MySQL support, making it ideal for dynamic web applications like WordPress, Joomla, or custom CMS. This guide provides a concise walkthrough for connecting to a MySQL database using PHP on AvaHost’s VPS or dedicated server, including secure practices and practical examples to ensure seamless development.

Prerequisites

  • AvaHost hosting plan (e.g., Shared Hosting or VPS Basic, €10/month) with MySQL support.

  • MySQL database created via cPanel or DirectAdmin.

  • Database credentials: name, username, password, and server (typically localhost).

  • SSH access or cPanel File Manager for uploading PHP scripts.

  • PHP 8.x and MySQL 5.7+ or MariaDB installed (default on AvaHost).

Connecting to MySQL with PHP (mysqli)

Here’s a simple example using mysqli (procedural style):

<?php
$servername = "localhost";
$username = "your_db_username";
$password = "your_db_password";
$database = "your_db_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);// Check connection
if (!$conn) {
die(“Connection failed: “ . mysqli_connect_error());
}
echo “Connected successfully”;
?>

Or using object-oriented mysql-cli

<?php
$conn = new mysqli("localhost", "your_db_username", "your_db_password", "your_db_name");
if ($conn->connect_error) {
die(“Connection failed: “ . $conn->connect_error);
}
echo “Connected successfully”;
?>

Executing a Query

To run a SQL query (like selecting data):

$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "User: " . $row["username"] . "<br>";


}


} else {


echo "0 results";


}

Security Tip: Use Prepared Statements

Always use prepared statements to prevent SQL injection:

$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$email = "user@example.com";
$stmt->execute();
$result = $stmt->get_result();

Why AvaHost for PHP + MySQL Projects?

  • PHP 8.x and MySQL 5.7+ / MariaDB supported

  • Fast NVMe storage for quick database access

  • Free SSL, SSH access, and optional caching tools

  • Affordable shared & VPS hosting plans with full LAMP stack

  • One-click install for MySQL-based platforms like WordPress, Joomla, and PrestaShop

Conclusion

Connecting to MySQL with PHP on AvaHost’s VPS or shared hosting is straightforward with mysqli and prepared statements, ensuring secure and efficient web applications. AvaHost’s NVMe SSDs, LiteSpeed, and cPanel make it easy to manage databases and deploy platforms like WordPress or custom CMS.