Home Backend Development PHP Problem How to write query statements in php database

How to write query statements in php database

Mar 29, 2023 am 11:32 AM

In the process of developing web applications, dealing with databases is inevitable. As a general-purpose programming language, PHP also has the ability to interact with databases. Developers can use it to perform various types of database query operations. However, it is not easy for beginners to correctly use PHP to interact with databases. This article aims to introduce you to how to correctly write PHP database query statements.

1. Connecting to the database in PHP

Before performing database query in PHP, we need to establish a connection with the database first. You can use PHP's own PDO (PHP Data Object) to connect to the database. Using PDO to connect to the database has the following benefits:

  1. Cross-platform: PDO supports many different databases, which can run in different operating systems.
  2. Prevent SQL injection: PDO automatically processes user-entered data to prevent SQL injection attacks.

Let’s take the MySQL database as an example to introduce how to use PDO to connect to the database.

  • Create a database connection

To use PDO to connect to the database, we need to provide information such as database type, host name, port, database name, user name and password. The following is an example of creating a connection:

try {
    $pdo = new PDO('mysql:host=localhost;port=3306;dbname=my_database', 'my_username', 'my_password');
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
Copy after login

If the connection is successful, the $pdo object will represent a connection established with the MySQL database instance, otherwise an exception will be thrown.

  • Execute SQL query

After connecting to the database, we can start executing SQL query. PDO provides a method to execute SQL queries (you can also perform SQL update and delete operations): exec(). This method receives a SQL statement as a parameter and returns an integer value indicating the number of affected rows or execution failure. For example, we can use the following code to create a table named "users":

$sql = 'CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)';

if ($pdo->exec($sql) !== false) {
    echo "Table users created successfully";
} else {
    echo "Error creating table: " . $pdo->errorInfo()[2];
}
Copy after login
  • Querying data

Querying data is the most commonly used in PHP and database interaction operation. We can use PDO to execute SELECT statements to query data. Here is an example of querying data:

$sql = "SELECT * FROM users WHERE id = ? OR email = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id, $email]);

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!empty($results)) {
    foreach ($results as $row) {
        echo $row['id'] . "\t" . $row['firstname'] . "\t" . $row['lastname'] . "\t" . $row['email'] . "\n";
    }
} else {
    echo "No results found";
}
Copy after login

Note that we use PDO's prepare() method to preprocess the SQL statement and bind the parameters in the query to placeholders. When executing a SQL query statement, use the execute() method to pass parameters and perform query operations. Finally, use the fetchAll() method to obtain the query results. The fetchAll() method returns an array, with each element representing a row of data in the query results.

2. Common SQL query statements

Using SQL query statements to interact with the database is a common operation in PHP. The following are common query statements.

  • SELECT

The SELECT statement is used to select to retrieve data from one or more tables. The syntax is as follows:

SELECT column1, column2, ... FROM table_name WHERE condition(s);
Copy after login

Among them, column1, column2 are the names of the columns to be retrieved, table_name is the name of the data source table to be retrieved, and the conditions after the WHERE keyword specify the conditions for filtering data. Here is a simple example:

SELECT * FROM users;
Copy after login

The above code will retrieve all the data in the "users" table.

  • UPDATE

The UPDATE statement is used to update data in an existing table. The syntax is as follows:

UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
Copy after login

Among them, value1, value2 are the values ​​to be updated, and condition specifies the condition of the row to be updated. The following is a simple example:

UPDATE users SET firstname='John', lastname='Doe' WHERE email='john.doe@example.com';
Copy after login

The above code will update the qualified data in the "users" table.

  • DELETE

The DELETE statement is used to delete data from an existing table. The syntax is as follows:

DELETE FROM table_name WHERE condition;
Copy after login

Among them, condition specifies the condition of the row to be deleted. The following is a simple example:

DELETE FROM users WHERE email='john.doe@example.com';
Copy after login

The above code will delete qualifying rows from the "users" table.

  • INSERT INTO

The INSERT INTO statement is used to insert new data into an existing table. The syntax is as follows:

INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
Copy after login

Among them, value1, value2, value3 are the values ​​to be inserted. Here is a simple example:

INSERT INTO users (firstname, lastname, email) VALUES ('John', 'Doe', 'john.doe@example.com');
Copy after login

The above code will insert a new row into the "users" table.

3. Summary

In this article, we introduced the use of PDO to connect to the database and common SQL query statements, hoping to help readers better understand and master the interaction between PHP and the database.

When performing database query operations, you need to pay attention to the following points:

  1. Try to use PDO preprocessing and bind variables to prevent SQL injection attacks.
  2. Avoid using SELECT *, and try to manually specify the name of the column to be queried.
  3. In PHP, before using check functions (such as isset() and empty()) to check a variable, you must first check whether the variable exists.

Hope this information will help you better use PHP to interact with databases, making it easier to build web applications.

The above is the detailed content of How to write query statements in php database. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

What are the best practices for deduplication of PHP arrays What are the best practices for deduplication of PHP arrays Mar 03, 2025 pm 04:41 PM

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

Can PHP array deduplication take advantage of key name uniqueness? Can PHP array deduplication take advantage of key name uniqueness? Mar 03, 2025 pm 04:51 PM

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

Does PHP array deduplication need to be considered for performance losses? Does PHP array deduplication need to be considered for performance losses? Mar 03, 2025 pm 04:47 PM

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

How to Implement message queues (RabbitMQ, Redis) in PHP? How to Implement message queues (RabbitMQ, Redis) in PHP? Mar 10, 2025 pm 06:15 PM

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

What Are the Latest PHP Coding Standards and Best Practices? What Are the Latest PHP Coding Standards and Best Practices? Mar 10, 2025 pm 06:16 PM

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

How Do I Work with PHP Extensions and PECL? How Do I Work with PHP Extensions and PECL? Mar 10, 2025 pm 06:12 PM

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

What are the optimization techniques for deduplication of PHP arrays What are the optimization techniques for deduplication of PHP arrays Mar 03, 2025 pm 04:50 PM

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

How to Use Reflection to Analyze and Manipulate PHP Code? How to Use Reflection to Analyze and Manipulate PHP Code? Mar 10, 2025 pm 06:12 PM

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea

See all articles