Connecting to MySQL and PostgreSQL databases from PHP 7 involves using the respective database extensions and their associated functions. Both require establishing a connection using connection parameters: server hostname, username, password, and database name. While the specific functions differ, the underlying principle remains the same.
MySQL Connection:
PHP's MySQLi extension (the improved MySQL extension) provides a robust way to interact with MySQL databases. The core function is mysqli_connect()
. This function takes the server hostname (or IP address), username, password, and database name as arguments. It returns a connection object upon successful connection, or false
on failure.
<?php $servername = "localhost"; $username = "your_username"; $password = "your_password"; $dbname = "your_database_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; $conn->close(); ?>
PostgreSQL Connection:
For PostgreSQL, PHP utilizes the pg_connect()
function from the pg_
extension. Similar to MySQLi, it requires the server address, username, password, and database name. The function returns a connection resource on success, or false
otherwise.
<?php $conn_string = "host=localhost port=5432 dbname=your_database_name user=your_username password=your_password"; $conn = pg_connect($conn_string); if (!$conn) { die("Error in connection: " . pg_last_error()); } echo "Connected successfully"; pg_close($conn); ?>
Remember to install the necessary PHP extensions (mysqli
for MySQL and pg_
for PostgreSQL) before running this code. This can usually be done through your system's package manager or by compiling PHP with the appropriate options.
As detailed above, the core functions are:
mysqli_connect()
(or object-oriented equivalent: new mysqli()
) is the primary function for establishing a connection. Other related functions, like mysqli_select_db()
(to select a specific database after connecting), are also often used.pg_connect()
is the fundamental function to connect to a PostgreSQL database. There are also other functions like pg_pconnect()
(for persistent connections) available.Robust error handling is crucial. Never rely on the absence of an error message to assume a successful connection. Always explicitly check for errors after attempting to connect.
MySQL:
The mysqli_connect()
function returns false
on failure. The mysqli
object's connect_error
property provides a detailed error message.
$conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
PostgreSQL:
pg_connect()
returns false
on failure. The pg_last_error()
function retrieves the last error message.
<?php $servername = "localhost"; $username = "your_username"; $password = "your_password"; $dbname = "your_database_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; $conn->close(); ?>
Beyond simple connection errors, consider using try-catch blocks for more comprehensive error handling, especially when performing database queries. Logging errors to a file or sending error notifications are also good practices.
Never hardcode database credentials directly in your PHP code. This is a major security risk. Instead, use environment variables, configuration files, or dedicated secret management systems.
getenv()
.config.php
) and store credentials there. Keep this file outside your webroot and ensure it's not accessible via the web. Use .htaccess
or similar mechanisms to protect it.Remember to regularly review and update your security practices. Keeping your database software and PHP updated is also crucial for patching known vulnerabilities.
The above is the detailed content of How to Connect to a Database (MySQL, PostgreSQL) with PHP 7?. For more information, please follow other related articles on the PHP Chinese website!