How to connect and call the database in php

silencement
Release: 2023-02-25 12:54:01
Original
5192 people have browsed it

How to connect and call the database in php

PHP needs to specify the following parameters to connect to the database

MySQL data source name or DSN: Specify 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: Indicates the name of the database to connect to.

Username and Password: Specify the username and password of the MySQL user used to connect to the MySQL database server. This account must have sufficient permissions to access the database specified above.

We will use:

Local MySQL database server, so that the DSN is localhost.

In classicmodels as a sample database.

Root account with blank password, just for demonstration.

Connecting to MySQL Steps

First, for convenience, we will create a new PHP file for database configuration, dbconfig.php. This file contains all configured parameters:

<?php
    $host = &#39;localhost&#39;;
    $dbname = &#39;classicmodels&#39;;
    $username = &#39;root&#39;;
    $password = &#39;&#39;;
Copy after login

Secondly, we create a new PHP file called phpmysqlconnect.php:

<?php
require_once &#39;dbconfig.php&#39;;
  
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());
}
Copy after login

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. We call the object's getMesage() method PDOException to get the detailed message to be displayed.

The above is the detailed content of How to connect and call the database in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!