To connect to the MySQL database, you need to create a database connection and use SQL queries to perform data operations (including retrieval, insertion, update, and deletion). Practical case demonstrates how to connect to a MySQL database and retrieve usernames. Specific steps include: creating a connection, executing the query, traversing the result set and printing the data.
<?php // 数据库主机名 $hostname = 'localhost'; // 数据库用户名 $username = 'db_username'; // 数据库密码 $password = 'db_password'; // 数据库名称 $database = 'db_name'; // 连接到数据库 $conn = mysqli_connect($hostname, $username, $password, $database); ?>
Once established Once connected, you can execute SQL queries.
<?php // 查询字符串 $query = "SELECT * FROM table_name"; // 执行查询 $result = mysqli_query($conn, $query); // 遍历结果集 while($row = mysqli_fetch_assoc($result)) { echo $row['column_name']; } ?>
<?php // 插入数据 $query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')"; // 执行查询 mysqli_query($conn, $query); ?>
<?php // 更新数据 $query = "UPDATE table_name SET column1 = 'new_value' WHERE id = 1"; // 执行查询 mysqli_query($conn, $query); ?>
<?php // 删除数据 $query = "DELETE FROM table_name WHERE id = 1"; // 执行查询 mysqli_query($conn, $query); ?>
Suppose you have a MySQL database named "users" and a table named "user_table" that contains usernames and passwords. Here's how to connect to that database and retrieve the username:
<?php // 连接到 MySQL 数据库 $conn = mysqli_connect('localhost', 'root', '', 'users'); // 查询 user_table $query = "SELECT username FROM user_table"; // 执行查询 $result = mysqli_query($conn, $query); // 遍历结果集并打印用户名 while($row = mysqli_fetch_assoc($result)) { echo $row['username'] . PHP_EOL; } ?>
The above is the detailed content of PHP database connection tutorial: beginner to database management master. For more information, please follow other related articles on the PHP Chinese website!