How to Connect Database in XAMPP (PHP)

In order to connect to a database, you will need to follow different methods based on the database system you are using. Here are the steps to connect common database systems on XAMPP:

  1. By default, XAMPP comes installed with the MySQL database. To connect to the MySQL database, you can use either the MySQLi or PDO extensions in PHP. Firstly, make sure the MySQL server is running. Then, you can use the following example code to connect to the MySQL database:
$servername = "localhost";
$username = "root";
$password = "";

// 创建连接
$conn = new mysqli($servername, $username, $password);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败:" . $conn->connect_error);
}

echo "成功连接到MySQL数据库";
  1. MariaDB is a fork of MySQL, and it has the same connection methods as MySQL. You can use the same sample code to connect to a MariaDB database.
  2. In order to connect to a PostgreSQL database, you will need to use the PDO extension in PHP. First, make sure the PostgreSQL server is running. Then, you can use the following sample code to connect to the PostgreSQL database:
$host = "localhost";
$dbname = "your_database";
$user = "your_username";
$password = "your_password";

try {
    $conn = new PDO("pgsql:host=$host;dbname=$dbname", $user, $password);
    echo "成功连接到PostgreSQL数据库";
} catch (PDOException $e) {
    die("连接失败:" . $e->getMessage());
}
  1. To connect to an SQLite database, you can utilize the PHP PDO extension. Ensure that the SQLite extension is enabled and then you can connect to the SQLite database using the sample code provided.
$database = "path/to/your/database.sqlite";

try {
    $conn = new PDO("sqlite:$database");
    echo "成功连接到SQLite数据库";
} catch (PDOException $e) {
    die("连接失败:" . $e->getMessage());
}

The above sample code is used only for connecting to the database and does not include any database operations. Depending on your specific needs, you may need to perform queries, inserts, updates, and so on.

bannerAds