Before connecting to the MySQL database, you must specify the following information:
MySQL data source name or DSN: Specifies the address of the MySQL database server. You can use an IP address or server name, for example, 127.0.0.1 or localhost
MySQL database name: The name of the database to be connected to.
Username and Password: Specifies the username and password of the MySQL user used to connect to the MySQL database server. The account must have sufficient permissions to access the database specified above.
We will use:
Local MySQL database server, so DSN is localhost.
In classicmodels as sample database.
The account with a blank root password is just for demonstration.
Steps to connect to MySQL
First, for convenience, we will create a new PHP file for the database configuration that contains all configured parameters:
<?php $host = 'localhost'; $dbname = 'classicmodels'; $username = 'root'; $password = '';
Secondly, we create a new PHP file called:
<?php require_once ''; try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); echo "Connected to $dbname at $host successfully."; } catch (PDOException $pe) { die("Could not connect to the database $dbname :" . $pe->getMessage()); }
How scripts work
Use the require_once function to include the file in the script.
In the try block, we create a new PDO object with three parameters: connection string, username and password. The connection string is changed from the variables $host and $dbname in the file
.
If the connection to the MySQL database is established successfully, we will display a success message. If there are any errors or exceptions, PHP will issue a PDOException containing a detailed error message
content. We call the object's getMesage() method PDOException to get the detailed message to be displayed.
The above are all the relevant knowledge points. Thank you for your support.