Home > Backend Development > PHP Tutorial > Getting Started with PHP Database Connectivity: A Step-by-Step Guide for Beginners

Getting Started with PHP Database Connectivity: A Step-by-Step Guide for Beginners

WBOY
Release: 2024-05-31 18:01:03
Original
1050 people have browsed it

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.

PHP 数据库连接入门:适合初学者的循序渐进指南

Getting Started with PHP Database Connection: A Step-by-Step Guide for Beginners

1. Install PHP and MySQL

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.

2. Create a MySQL database

Log in to your MySQL database server and execute the following command:

CREATE DATABASE database_name;
Copy after login

3. Create a MySQL user

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;
Copy after login

4. Connect to the MySQL database

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 "连接成功";
?>
Copy after login

Practical case: Get from the database Data

// 准备查询
$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>";
}
Copy after login

Conclusion

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!

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