MySQL and PHP are the foundation of dynamic websites across the internet. PHP is a server-side scripting language that runs on the web server and generates HTML pages on the fly. MySQL is a relational database management system that stores and retrieves the data your website needs. Together, they power everything from simple contact forms to complex content management systems like WordPress, Joomla and Drupal.
If you are new to server-side development, or if you have been building static HTML pages and want to take the next step, this guide introduces the core concepts of MySQL and PHP and shows you how to get started on your hosting account.
What Is PHP?
PHP (which originally stood for "Personal Home Page" but now stands for "PHP: Hypertext Preprocessor") is a scripting language designed specifically for web development. Unlike HTML, which is sent directly to the browser, PHP code is processed on the server before the result is sent to the visitor's browser.
This server-side processing allows PHP to do things that HTML alone cannot:
- Read and write data to a database
- Process form submissions
- Send email from your website
- Generate dynamic page content based on user input, database queries or other conditions
- Manage user sessions and authentication
- Read and write files on the server
PHP files typically have a .php extension. When a visitor requests a PHP file, the web server passes it to the PHP interpreter, which executes the code and returns the resulting HTML to the browser. The visitor never sees the PHP source code, only the HTML output.
What Is MySQL?
MySQL is an open-source relational database management system. It stores data in structured tables with rows and columns, similar to a spreadsheet but with much greater power and flexibility. You interact with MySQL using SQL (Structured Query Language), a standard language for creating, reading, updating and deleting data.
In a typical web application, MySQL stores things like:
- Blog posts, pages and articles
- User accounts and profiles
- Product catalogues and pricing
- Customer orders and transactions
- Configuration settings
- Contact form submissions
MySQL is the most popular database system on the web and is included with virtually every shared hosting plan. It is fast, reliable and well-documented, making it an excellent choice for both beginners and experienced developers.
Creating a MySQL Database in cPanel
Before you can use a database in your PHP application, you need to create it through cPanel. Here is the process:
Step 1: Create the Database
- Log in to cPanel and find "MySQL Databases" in the Databases section.
- In the "New Database" field, enter a name for your database. cPanel will prefix it with your hosting username (for example, if your username is "mysite" and you enter "blog", the database name will be "mysite_blog").
- Click "Create Database."
Step 2: Create a Database User
- On the same page, scroll down to the "MySQL Users" section.
- Enter a username and a strong password for the database user. cPanel will prefix the username with your hosting account name.
- Click "Create User."
Step 3: Add the User to the Database
- Scroll down to "Add User To Database."
- Select the user and the database from the dropdown menus.
- Click "Add."
- On the privileges screen, select "All Privileges" (or choose specific permissions if you want to restrict access) and click "Make Changes."
Write down the full database name, username and password. You will need these to connect to the database from your PHP code.
Your First PHP Page
Let us create a simple PHP page to verify that PHP is working on your hosting account. Using cPanel's File Manager or your FTP client, create a new file called hello.php in your public_html directory with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Test</title>
</head>
<body>
<h1>Hello from PHP</h1>
<p>The current date and time on the server is:
<?php echo date('l, j F Y, H:i:s'); ?></p>
</body>
</html>
Visit yourdomain.com/hello.php in your browser. If PHP is working correctly, you will see the heading "Hello from PHP" followed by the current server date and time. The <?php ... ?> tags mark the beginning and end of PHP code within an HTML page.
Connecting PHP to MySQL
Now let us connect PHP to the MySQL database you created. The modern way to connect to MySQL from PHP is using the MySQLi (MySQL Improved) extension or PDO (PHP Data Objects). We will use MySQLi in these examples as it is straightforward and widely used.
Create a new file called dbtest.php in your public_html directory:
<?php
// Database connection settings
$host = 'localhost';
$username = 'mysite_bloguser'; // Replace with your database username
$password = 'your_password'; // Replace with your database password
$database = 'mysite_blog'; // Replace with your database name
// Create connection
$conn = new mysqli($host, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
echo 'Connected to MySQL successfully.';
// Close connection
$conn->close();
?>
Replace the placeholder values with the actual database name, username and password you created in cPanel. Visit yourdomain.com/dbtest.php and you should see "Connected to MySQL successfully." If you see an error, double-check your credentials and ensure the user is properly assigned to the database.
Security note: The example above is for testing purposes only. In a production environment, you should store database credentials in a configuration file outside the public_html directory (or in a file protected by .htaccess) so they cannot be accessed by web visitors. Always remove test files after you have finished testing.
Creating a Table and Inserting Data
Let us create a simple table and insert some data. This example creates a "messages" table that could be used to store contact form submissions:
<?php
$host = 'localhost';
$username = 'mysite_bloguser';
$password = 'your_password';
$database = 'mysite_blog';
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
// Create a table
$sql = "CREATE TABLE IF NOT EXISTS messages (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) NOT NULL,
message TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo 'Table created successfully.<br>';
} else {
echo 'Error creating table: ' . $conn->error . '<br>';
}
// Insert a row
$sql = "INSERT INTO messages (name, email, message)
VALUES ('John Murphy', '[email protected]', 'Hello, I would like more information about your hosting plans.')";
if ($conn->query($sql) === TRUE) {
echo 'Record inserted successfully.<br>';
} else {
echo 'Error inserting record: ' . $conn->error . '<br>';
}
$conn->close();
?>
This script creates a table with columns for an auto-incrementing ID, a name, an email address, a message and a timestamp. It then inserts one row of sample data.
Retrieving Data from MySQL
Once you have data in your database, you can retrieve and display it with PHP:
<?php
$host = 'localhost';
$username = 'mysite_bloguser';
$password = 'your_password';
$database = 'mysite_blog';
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
$sql = "SELECT id, name, email, message, created_at FROM messages ORDER BY created_at DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<h2>Messages</h2>';
while ($row = $result->fetch_assoc()) {
echo '<div style="border:1px solid #ccc; padding:10px; margin:10px 0;">';
echo '<strong>' . htmlspecialchars($row['name']) . '</strong> ';
echo '(' . htmlspecialchars($row['email']) . ')<br>';
echo '<p>' . htmlspecialchars($row['message']) . '</p>';
echo '<small>' . $row['created_at'] . '</small>';
echo '</div>';
}
} else {
echo 'No messages found.';
}
$conn->close();
?>
Notice the use of htmlspecialchars() when displaying data. This function converts special characters to HTML entities, preventing cross-site scripting (XSS) attacks. Always use htmlspecialchars() when outputting user-supplied data to the browser.
Using phpMyAdmin
phpMyAdmin is a web-based tool included with cPanel that lets you manage your MySQL databases through a graphical interface. You can access it from the Databases section of cPanel.
With phpMyAdmin, you can:
- Browse the contents of your tables
- Run SQL queries directly
- Import and export databases (useful for backups and migrations)
- Create and modify tables without writing SQL
- Search for specific data across your database
- Manage database users and permissions
phpMyAdmin is particularly useful when you need to examine what is in your database, troubleshoot data issues, or import a database backup from another server.
Security Best Practices for PHP and MySQL
When building PHP applications that interact with a database, security should be a priority from the start:
- Use prepared statements: Never insert user input directly into SQL queries. Use prepared statements with parameter binding to prevent SQL injection attacks.
- Validate and sanitise input: Check that user input matches expected formats (for example, verify that an email field contains a valid email address) before processing it.
- Escape output: Always use
htmlspecialchars()when displaying data in HTML to prevent XSS attacks. - Keep credentials secure: Store database connection details in a configuration file that is not accessible from the web.
- Use strong database passwords: Your database user password should be long and random, just like any other important password.
- Limit database permissions: Give your database user only the permissions it needs. A read-only section of your site does not need INSERT, UPDATE or DELETE privileges.
Next Steps
This guide has covered the fundamentals of MySQL and PHP on a web hosting account. From here, you might consider:
- Building a simple contact form that saves submissions to a MySQL database
- Creating a basic content management system to manage pages on your site
- Installing WordPress (which uses MySQL and PHP) to get a full-featured CMS up and running quickly
- Learning about PHP frameworks that provide structure and security tools for larger applications
The combination of PHP and MySQL gives you the tools to build virtually any type of website, from simple dynamic pages to full web applications. Start with small projects, follow security best practices from the beginning, and build your skills incrementally.
PHP and MySQL are included with every Web Hosting Ireland plan. Our Starter plan includes 1 MySQL database, while our Business plan offers unlimited databases. All plans include PHP and CGI support. View our hosting plans.