Summary
Learn how to connect to a MySQL database using PHP 8.x to PHP 7.x. This guide covers the modern mysqli_* functions required for current PHP versions, with legacy mysql_* functions for older systems.
Before you start checklist
Make sure you’ve done the following steps before you start:
- Your DomainsFoundry account must support MySQL and PHP.
- You have created a MySQL database.
- Your MySQL database name, username and password. See What are my MySQL Settings?
Example for PHP 8.x to PHP 7.x (Current Versions)
The following example opens a connection to a MySQL server using mysqli (MySQL Improved Extension), which is the standard for PHP 7.0 and later, including all PHP 8.x versions:
<?php
//Set MySQL Configuration Settings
$mysql_server = 'localhost';
$mysql_db = 'database';
$mysql_user = 'username';
$mysql_password = 'password';
//Connect to MySQL using mysqli
$con = mysqli_connect($mysql_server, $mysql_user, $mysql_password, $mysql_db);
//Check connection
if (!$con) {
die('Could not connect: ' . mysqli_connect_error());
}
//Some code
echo "Congratulations - you've connected to your DomainsFoundry database!";
//Close connection
mysqli_close($con);
?>
Legacy Example for PHP 5.x and earlier
Note: The mysql_* functions shown below are deprecated and were removed in PHP 7.0. This code will NOT work on PHP 7.x or PHP 8.x. Use the mysqli example above for current PHP versions.
<?php
//Set MySQL Configuration Settings
$mysql_server = 'localhost';
$mysql_db = 'database';
$mysql_user = 'username';
$mysql_password = 'password';
//Connect to MYSQL
$con = mysql_connect($mysql_server, $mysql_user, $mysql_password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//Select a database
$db_selected = mysql_select_db($mysql_db, $con);
if (!$db_selected) {
die('Could not select database: ' . mysql_error());
}
//Some code
echo "Congratulations - you've connected to your DomainsFoundry database!";
//Close connection
mysql_close($con);
?>
