Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Connect to MySQL with PHP

This guide shows you how to write a short PHP file that connects to a MySQL database.

Databases2 min read7 steps

What do these words mean?

MySQL is a popular database system. A database is a store for information, like a filing cabinet.

PHP is a programming language that runs on web servers. Many websites, including WordPress, use it.

PDO and MySQLi are two built-in PHP tools for talking to databases. This guide uses MySQLi, which is simple to read.

Before you start

  • Create a database and a database user in your hosting control panel.
  • Give the user rights on the database.
  • Write down the database name, user name, password and host. The host is usually localhost, which means the same computer as your website.

Steps

  1. Log in to your hosting control panel and open File Manager.
  2. Go to your website folder, often public_html.
  3. Click + File and name it dbtest.php.
  4. Right-click the file and choose Edit.
  5. Paste this code. Replace the four values with your own:
<?php
$host = "localhost";
$user = "your_user";
$pass = "your_password";
$name = "your_database";

$conn = new mysqli($host, $user, $pass, $name);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";
$conn->close();
?>
  1. Click Save Changes.
  2. Open yourdomain.com/dbtest.php in your browser.

The code makes a connection with your login. If it fails, it prints the reason. If it works, it says "Connected successfully" and closes the link.

The PDO way

Many developers prefer PDO. Here is the same job:

<?php
try {
    $pdo = new PDO("mysql:host=localhost;dbname=your_database", "your_user", "your_password");
    echo "Connected successfully";
} catch (PDOException $e) {
    echo "Failed: " . $e->getMessage();
}
?>

This tries to connect and prints a message either way.

Clean up

When the test is done, delete dbtest.php. It holds your password in plain text.

If it fails

  • Access denied: check the user name and password. Check that the user is linked to the database.
  • Unknown database: check the name. On shared hosting it often starts with your account name.
  • Cannot connect: check the host. Ask Hostvento support for the right one.
Tip: Never share code that shows your real password.

Quick recap

  • PHP connects to MySQL with host, user, password and database name.
  • Use new mysqli(...) or new PDO(...).
  • Test with a small file, then delete it.
  • Read the error message if the connection fails.