Home  >  Article  >  Backend Development  >  PHP database connection tutorial: beginner to database management master

PHP database connection tutorial: beginner to database management master

WBOY
WBOYOriginal
2024-06-01 22:27:591040browse

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 database connection tutorial: beginner to database management master

PHP Database Connection Tutorial: Beginner to Database Management Master

Prerequisite

  • PHP is installed on the local computer
  • Database management system (such as MySQL, PostgreSQL or MariaDB)

1. Create a database connection

<?php
// 数据库主机名
$hostname = 'localhost';
// 数据库用户名
$username = 'db_username';
// 数据库密码
$password = 'db_password';
// 数据库名称
$database = 'db_name';

// 连接到数据库
$conn = mysqli_connect($hostname, $username, $password, $database);
?>

2. Execute the SQL query

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'];
}
?>

3. Insert data

<?php
// 插入数据
$query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";

// 执行查询
mysqli_query($conn, $query);
?>

4. Update data

<?php
// 更新数据
$query = "UPDATE table_name SET column1 = 'new_value' WHERE id = 1";

// 执行查询
mysqli_query($conn, $query);
?>

5. Delete data

<?php
// 删除数据
$query = "DELETE FROM table_name WHERE id = 1";

// 执行查询
mysqli_query($conn, $query);
?>

Practical case: Connect to MySQL database

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!

Statement:
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