Tutorial
How to connect PHP to MySQL
A working PDO connection, why the credentials belong outside the web root, and how to read the error when it fails.
- Use PDO to connect PHP to MySQL. Copy the connection block into your script and update the database name, user and password.
- Always run queries with prepared statements (the
?placeholders) to stop SQL injection. - If the connection fails, check for wrong credentials, a white screen from hidden errors, or hitting the 5-connection limit on free hosting.
- Our free hosting is for learning and low-traffic sites. If you need mail, more visitors, or guaranteed uptime, use paid hosting elsewhere.
You need to connect PHP to MySQL. The right tool for it is PDO. Here is the working code.
Start by making sure you have a database and a user. If you haven’t done that yet, follow the guide on how to create a MySQL database first. You will need the database name, username and password.
The PDO connection
<?php
$host = 'localhost';
$db = 'your_database_name';
$user = 'your_database_user';
$pass = 'your_password';
$charset = 'utf8mb4';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass, $options);
} catch (\PDOException $e) {
// Do NOT print $e->getMessage() to the browser
error_log("Database connection failed: " . $e->getMessage());
die("Sorry, we are having a technical problem.");
}
?>
Copy this block. Change the database name, user and password to the ones you created. Put this at the top of every page that needs the database.
Key details in the code:
PDO::ERRMODE_EXCEPTIONmakes PHP throw an exception when the database fails. Without this, you get silent failures that are hard to debug.PDO::ATTR_EMULATE_PREPARES => falseturns off emulated prepared statements. This gives you real prepared statements from MySQL.- The
catchblock logs the real error to the server log and shows the visitor a generic message. Never show the raw error text. It contains the database username, the host name and sometimes the password.
Run a query with prepared statements
Your connection works. Now you need data. Always use prepared statements, even for simple queries. They prevent SQL injection, which is the fastest way to get your site defaced.
<?php
require 'db.php'; // or wherever you put the connection block above
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$_GET['email']]);
$user = $stmt->fetch();
if ($user) {
echo "Hello, " . htmlspecialchars($user['name']);
} else {
echo "User not found.";
}
?>
The ? placeholders get replaced by the array you pass to execute(). The
values are sent separately to the database, so they cannot be mistaken for SQL
commands.
Never put variables directly into the query string. Never write
"SELECT * FROM users WHERE id = $id". That is how your database gets deleted.
Why your connection might fail
Three things go wrong most often.
The credentials are wrong
You will get an “Error establishing a database connection” page. The cause is usually a typo in the database name, username or password. Check them against what you created in the control panel. The error establishing a database connection page lists every cause and what to do about each.
PHP shows a blank page
If you get a white screen, PHP is hiding errors from you. This happens when display_errors is off in the php.ini. Add this line to the top of your script for testing:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
Remove it before you put the site live. A live site that shows PHP errors is a security hole. Read the white screen of death guide for more.
You hit the connection limit
On the free hosting plan, MySQL allows 5 concurrent connections per account. Each script you run counts as one connection. If you open a PDO object and never let it close, or if you have multiple scripts running at the same time, you can use all 5 slots. The error message says “Too many connections”. The fix is to close your connections when you are done.
$pdo = null; // closes the connection
Or just let the script end. PHP closes the connection automatically when the variable goes out of scope. The real cause is scripts that do not finish quickly or code that creates multiple PDO objects on the same page. Check the too many connections article for the full diagnostic.
Connect to MySQL on paid hosting instead
Our free hosting has limits that matter for database applications.
- 10 concurrent PHP processes per account. If your site is popular, the 11th visitor waits.
- 50,000 requests per day. That is about one request every 1.7 seconds averaged. A single busy WordPress site can burn through that.
- No outbound email. You cannot send password resets or contact form mail.
If your site needs mail, needs to handle more than a handful of visitors at once, or needs a guaranteed uptime, you should use paid hosting from someone else. Our service is for learning, prototyping and low-traffic personal sites. That is deliberate.