Connecting to MySQL with PHP (Firstserv Guide)

When connecting to your MySQL database from a website or script hosted on the same Firstserv cPanel account, you should always use:

localhost

👉 This ensures the connection is made internally on the server, which is faster and more secure.


Example PHP Connection Code

Below is a simple example using the MySQLi extension:

 
 
 
 
 
 
PHP
 
 
<?php
$hostname = "localhost"; // Always use localhost for local connections
$database = "cpaneluser_databasename"; // Your full database name
$username = "cpaneluser_dbuser"; // Your database username
$password = "your_secure_password"; // Your database password
 
$con = mysqli_connect($hostname, $username, $password, $database);
 
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
 
echo "Connected successfully";
?>
 
 

Replace With Your Details

Make sure you update:

  • cpaneluser_databasename → Your full database name
  • cpaneluser_dbuser → Your database username
  • your_secure_password → Your database user password

📌 Remember: cPanel automatically adds your account prefix to database and user names.


Important Notes

  • ✅ The hostname should always be localhost for scripts running on your hosting account
  • ✅ Use MySQLi or PDO (modern, supported methods)
  • ❌ Avoid using older functions like mysql_connect (deprecated)

Troubleshooting

If the connection fails:

  • ✅ Check your database name and username are correct
  • ✅ Ensure the user has been assigned to the database with ALL PRIVILEGES
  • ✅ Confirm the password is correct

Summary

  • Use localhost for MySQL connections within your hosting
  • Use MySQLi or PDO for secure, modern PHP connections
  • Ensure database credentials match your cPanel setup

Need Help?

If you’re unsure about your database details or need help connecting your application, the Firstserv support team is always happy to assist.

 

  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

Enable Redis on a Premium PCI-DSS compliant plan

Using Redis on Firstserv Hosting What is Redis? Redis (Remote Dictionary Server) is an...

Shell access to your server using SSH (PuTTY for Windows)

Accessing Your Server via SSH (Firstserv Guide) All Firstserv...

Enable or disable SSH (Secure Shell) access

Enabling SSH Access (Firstserv Guide) Firstserv provides secure,...

Connect to MySQL using MySQL Workbench

Connecting to MySQL via SSH Tunnel (Firstserv Guide – MySQL...

Block bad spiders to save bandwidth

Blocking Bad Bots & Search Crawlers (Firstserv Guide) Search...