PHP and MySQL database connection guide: Install PHP and MySQL; Create a MySQL database and create a user with access rights; Use PHP code to connect to the MySQL database; Practical case: Get data from the database.
Getting Started with PHP Database Connection: A Step-by-Step Guide for Beginners
Make sure your server has PHP and MySQL installed. You can refer to the official documentation to learn how to install these components on your system.
Log in to your MySQL database server and execute the following command:
CREATE DATABASE database_name;
Create a user with MySQL user with new database access rights:
CREATE USER 'username'@'localhost' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost'; FLUSH PRIVILEGES;
Use the following PHP code to connect to the MySQL database:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } echo "连接成功"; ?>
// 准备查询 $sql = "SELECT * FROM users"; // 执行查询 $result = $conn->query($sql); // 循环遍历查询结果 while($row = $result->fetch_assoc()) { echo "ID: " . $row["id"] . "<br>"; echo "姓名: " . $row["name"] . "<br>"; echo "电子邮件: " . $row["email"] . "<br><br>"; }
Congratulations! You have successfully established a connection between PHP and MySQL and retrieved data from the database. If you need more advanced functionality, you can explore the PHP Data Objects (PDO) extension.
The above is the detailed content of Getting Started with PHP Database Connectivity: A Step-by-Step Guide for Beginners. For more information, please follow other related articles on the PHP Chinese website!