PHP is a widely-used server-side scripting language, and MySQL is a popular relational database management system. PHP7, as the latest version, brings significant performance improvements and new features. This article will guide you on how to connect PHP7 with MySQL and create a simple data query program.
Before starting, ensure PHP7 and MySQL are correctly installed on your system, and you can access the MySQL database smoothly. If not installed yet, please refer to official documentation to complete installation and configuration.
Visit the official PHP website (https://www.php.net) to download the installation package and follow the instructions to install PHP7.
Go to the official MySQL website (https://www.mysql.com) to download the installer and complete the installation and basic setup.
Before proceeding, create a database and table to store the query data. You can use the MySQL command line or graphical tools like phpMyAdmin.
CREATE DATABASE mydatabase;
USE mydatabase;
CREATE TABLE mytable (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT(11),
email VARCHAR(50)
);
In PHP, the MySQL connection can be made using either the mysqli or PDO extension. This article demonstrates using mysqli.
// Create database connection
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mydatabase';
$mysqli = new mysqli($host, $username, $password, $database);
// Check if connection is successful
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
}
echo 'Successfully connected to the database!';
The code defines connection parameters, creates a mysqli object, and checks connection status via connect_error.
After a successful connection, execute SQL queries to retrieve data.
// Execute query
$sql = 'SELECT * FROM mytable';
$result = $mysqli->query($sql);
// Check if query succeeded
if ($result === false) {
die('Query failed: ' . $mysqli->error);
}
// Loop through results and output data
while ($row = $result->fetch_assoc()) {
echo 'ID: ' . $row['id'] . ' ';
echo 'Name: ' . $row['name'] . ' ';
echo 'Age: ' . $row['age'] . ' ';
echo 'Email: ' . $row['email'] . '<br>';
}
// Free result set
$result->free();
The example uses query() to run the SQL, fetch_assoc() to iterate over the result set, outputting each row’s fields, then frees memory.
After all operations, close the database connection.
// Close connection
$mysqli->close();
Calling the close() method of the mysqli object ensures the connection is properly closed.
This article provides a systematic introduction to connecting PHP7 with MySQL, from environment setup, database operations, querying to closing connections. Mastering these basics effectively supports developing dynamic websites or applications based on PHP. Hope this tutorial helps you quickly get started with PHP and MySQL integration.