Home Backend Development PHP Tutorial How to use PHP database connection to implement data query and update

How to use PHP database connection to implement data query and update

Sep 09, 2023 am 10:07 AM
data query Data Update php database connection

How to use PHP database connection to implement data query and update

How to use PHP database connection to implement data query and update

1. MySQL database connection

Before using database connection in PHP, you need to make sure The MySQL database server has been correctly installed and configured. Next, we will learn how to use PHP to connect to the MySQL database and perform data query and update operations.

  1. Installation and configuration of MySQL

First, you need to install the MySQL database server. Depending on the operating system, you can choose to use the installation package officially provided by MySQL, or install it through an integrated development environment (such as XAMPP, WAMP, etc.).

After the installation is complete, you need to create a database and data table. It can be created using MySQL's command line tools or visual tools (such as phpMyAdmin).

  1. Connecting to the database

In PHP, you can use MySQLi (MySQL Improved Extension) or PDO (PHP Data Objects) extension to connect to the MySQL database. Here we take MySQLi as an example:

<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// 创建数据库连接
$conn = new mysqli($host, $username, $password, $dbname);

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

In the above code, we use the new mysqli() method to create a database connection and pass in the connection information. If the connection fails, an error message will be output; if the connection is successful, "Connection successful" will be output.

  1. Query data

After successfully connecting to the database, we can use SQL statements to perform data query operations.

<?php
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>";
    }
} else {
    echo "没有结果";
}
?>
Copy after login

In the above code, we use the SELECT statement to query all the data in the users table, and obtain the associative array of each result through the fetch_assoc() method, and then for processing.

  1. Update data

In addition to querying data, we can also use SQL statements to perform data update operations.

<?php
$sql = "UPDATE users SET age = 20 WHERE id = 1";

if ($conn->query($sql) === TRUE) {
    echo "更新成功";
} else {
    echo "更新失败:" . $conn->error;
}
?>
Copy after login

In the above code, we use the UPDATE statement to update the age field of the record with id 1 in the users table to 20.

  1. Close the database connection

After using the database, remember to close the database connection and release resources:

<?php
$conn->close();
?>
Copy after login

2. PDO database connection

Similar to MySQLi, the steps to connect to the database using PDO extension are not much different.

  1. Connect to database
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// 创建数据库连接
try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "连接成功";
} catch(PDOException $e) {
    die("连接失败:" . $e->getMessage());
}
?>
Copy after login
  1. Query data
<?php
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->rowCount() > 0) {
    while($row = $result->fetch(PDO::FETCH_ASSOC)) {
        echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>";
    }
} else {
    echo "没有结果";
}
?>
Copy after login
  1. Update data
<?php
$sql = "UPDATE users SET age = 20 WHERE id = 1";

if ($conn->exec($sql) === TRUE) {
    echo "更新成功";
} else {
    echo "更新失败";
}
?>
Copy after login
  1. Close the database connection

The operation is the same as MySQLi. After using the database, remember to close the database connection:

<?php
$conn = null;
?>
Copy after login

Summary:

Through the above code example , we learned how to use PHP database connections to implement data query and update operations. MySQLi and PDO are commonly used PHP database extensions. You can choose the appropriate extension based on personal preferences and project needs. In order to ensure the security and reliability of data, attention must also be paid to preventing security issues such as SQL injection. I hope this article can help you use database connections in PHP.

The above is the detailed content of How to use PHP database connection to implement data query and update. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement real-time data updates in ECharts How to implement real-time data updates in ECharts Dec 17, 2023 pm 02:07 PM

ECharts is an open source visual chart library that supports various chart types and rich data visualization effects. In actual scenarios, we often need to display real-time data, that is, when the data source changes, the chart can be updated immediately and present the latest data. So, how to achieve real-time data update in ECharts? The following is a specific code demonstration example. First, we need to introduce ECharts’ js files and theme styles: &lt;!DOCTYPEhtml&gt;

Solve the problem of real-time update of Vue asynchronous request data Solve the problem of real-time update of Vue asynchronous request data Jun 30, 2023 pm 02:31 PM

How to solve the problem of real-time update of asynchronous request data in Vue development. With the development of front-end technology, more and more web applications use asynchronous request data to improve user experience and page performance. In Vue development, how to solve the problem of real-time update of asynchronous request data is a key challenge. Real-time update means that when the asynchronously requested data changes, the page can be automatically updated to display the latest data. In Vue, there are multiple solutions to achieve real-time updates of asynchronous data. 1. Responsive machine using Vue

How to dynamically bind and update form data in Vue How to dynamically bind and update form data in Vue Oct 15, 2023 pm 02:24 PM

How to dynamically bind and update form data in Vue With the continuous development of front-end development, forms are an interactive element that we often use. In Vue, dynamic binding and updating of forms is a common requirement. This article will introduce how to dynamically bind and update form data in Vue, and provide specific code examples. 1. Dynamic binding of form data Vue provides the v-model instruction to achieve two-way binding of form data. Through the v-model directive, we can compare the value of the form element with the Vue instance

Discuz online people counting function setting tips Discuz online people counting function setting tips Mar 10, 2024 am 09:33 AM

The setting skills of Discuz’s online people counting function require specific code examples. With the development of the Internet, the website’s online people counting function has gradually become one of the essential functions for website managers. Discuz is a very popular forum program. The setting of its online people statistics function is very important. It can provide website administrators with real-time access data, helping them better understand the access status of the website, so as to make corresponding adjustments and optimizations. . This article will introduce the setting skills of Discuz’s online people counting function and provide some suggestions.

Real-time data processing of MySql: how to achieve timely update of data Real-time data processing of MySql: how to achieve timely update of data Jun 16, 2023 am 08:27 AM

In database application development, the efficiency and accuracy of data processing are crucial. As data grows, real-time data processing becomes increasingly important to many businesses. In this case, MySQL has become one of the most popular relational databases, and vendors and developers need to focus on how to use MySQL to process real-time data. When working with real-time data, the main goal is to capture and process the data quickly and accurately. In order to achieve this, the following methods can be used: Indexing Indexing is the key to making the database quickly locate data.

How to use MySQL to implement data update operations in C# How to use MySQL to implement data update operations in C# Aug 01, 2023 pm 04:09 PM

How to use MySQL to implement data update operations in C# MySQL is a widely used relational database that provides powerful data management and query functions. In C# development, we often need to store data in MySQL and update the data when needed. This article will introduce how to use MySQL and C# to implement data update operations, and provide corresponding code examples. Step 1: Install MySQLConnector/NET Before starting, we need to install MySQLCo

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

How to query and update data in CakePHP? How to query and update data in CakePHP? Jun 03, 2023 pm 02:11 PM

CakePHP is a popular PHP framework that provides convenient ORM (Object Relational Mapping) functionality that makes querying and updating the database very easy. This article will introduce how to query and update data in CakePHP. We'll start with simple queries and updates and work our way up to see how to use conditions and associated models to query and update data more complexly. Basic Query First, let's see how to make the simplest query. Let's say we have a data table called "Users" and we want

See all articles