Home Backend Development PHP Problem How to use PHP to perform one-to-many correlation query

How to use PHP to perform one-to-many correlation query

Apr 19, 2023 am 10:05 AM

When using PHP for database operations, it is often necessary to perform one-to-many correlation queries. This kind of query can relate a piece of data in one table to multiple pieces of data in another table. In PHP, a one-to-many relational query usually results in a two-dimensional array, in which each element represents a main table record, and the corresponding values ​​are records in multiple related tables.

This article will introduce how to use PHP to perform one-to-many related queries and get the results of a two-dimensional array.

1. What is a one-to-many relational query?

In the database, if there is a primary and foreign key relationship between two tables, then you can perform a one-to-many association query. In this relationship, one record in one table corresponds to multiple records in another table.

For example, there is a "student table" and a "score table". Each student in the "student table" corresponds to records in multiple "score tables". This relationship can be bound using primary keys and foreign keys, as shown below:

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `score` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) DEFAULT NULL,
  `score` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `student_id` (`student_id`),
  CONSTRAINT `score_ibfk_1` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login

In the "Student Table", each record includes a unique identifier ID and a name NAME. In the "score table", each record includes the same unique identifier ID and a corresponding STUDENT_ID, which represents which student the record belongs to; in addition, there is a SCORE field, which represents the student's score.

2. How to perform one-to-many correlation query?

In PHP, you can perform one-to-many related queries by using the JOIN keyword. JOIN is a keyword in SQL that is used to join the same columns in two or more tables together and generate a large table.

In the above example, if you want to associate the student table with the grade table, you can use the following SQL statement:

SELECT student.*, score.score
FROM student
LEFT JOIN score ON student.id = score.student_id;
Copy after login

In this statement, first select all fields in the student table , and then connect the score table and student table through LEFT JOIN and ON keywords. The condition of the connection is that the ID field in the student table is equal to the STUDENT_ID field in the grades table. Finally, select the columns to be displayed through the SELECT statement and get the result of a two-dimensional array.

In PHP's PDO object, you can use the query method to execute the above SQL statement, and use the fetchAll method to get the result of a two-dimensional array:

$db = new PDO('mysql:host=localhost;dbname=mydb', 'myuser', 'mypassword');
$stmt = $db->query('SELECT student.*, score.score
                    FROM student
                    LEFT JOIN score ON student.id = score.student_id');
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Copy after login

In the above code, first create Get a PDO object, then use the query method to execute the SQL statement, and finally use the fetchAll method to get the result.

3. How to process one-to-many association query results into a two-dimensional array?

When performing a one-to-many association query, the data in multiple tables need to be combined into a two-dimensional array result. Each element of this two-dimensional array represents a record in a main table, and the corresponding values ​​are records in multiple related tables.

The following is a method of processing one-to-many association query results into a two-dimensional array:

$data = array();
foreach ($result as $row) {
    $id = $row['id'];
    if (!isset($data[$id])) {
        $data[$id] = $row;
        $data[$id]['scores'] = array();
    }
    if (!empty($row['score'])) {
        $data[$id]['scores'][] = $row['score'];
    }
}
Copy after login

In the above code, first create an empty array $data, which will be used as the final The result of the two-dimensional array. Then use a foreach loop to traverse each record in the query results and save the primary key ID of each record in the $id variable.

Next, check whether there is already an element with the primary key $id in the $data array. If it does not exist, the element is inserted into the $data array and an empty array named "scores" is created to hold all records related to the primary key. If it already exists, there is no need to insert it and the existing element is used directly.

When traversing records, if a record in the "score table" is found, add the SCORE field of the record to the scores array. Since one main table record corresponds to multiple related table records, the scores array needs to be saved as a two-dimensional array.

When the loop ends, the final two-dimensional array result is stored in the $data array. Each element represents a main table record, and the corresponding values ​​are multiple records in the related table.

4. Example

The following is a complete example that demonstrates how to perform a one-to-many association query and process the result into a two-dimensional array:

$db = new PDO('mysql:host=localhost;dbname=mydb', 'myuser', 'mypassword');
$stmt = $db->query('SELECT student.*, score.score
                    FROM student
                    LEFT JOIN score ON student.id = score.student_id');
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

$data = array();
foreach ($result as $row) {
    $id = $row['id'];
    if (!isset($data[$id])) {
        $data[$id] = $row;
        $data[$id]['scores'] = array();
    }
    if (!empty($row['score'])) {
        $data[$id]['scores'][] = $row['score'];
    }
}

print_r($data);
Copy after login

In the above In the example, first create a PDO object and use the query method to execute the SQL statement. Then use the fetchAll method to get the query results.

Next, use a foreach loop to traverse each record in the query results and process it into a two-dimensional array. Finally, use the print_r function to output the results.

5. Conclusion

This article introduces how to perform one-to-many related queries in PHP and process the results into a two-dimensional array. When processing the results, you need to use a loop to traverse the query results and convert them into a two-dimensional array. After processing all the records, you can get the result of a two-dimensional array, in which each element represents a main table record, and the corresponding values ​​are records in multiple related tables.

The above is the detailed content of How to use PHP to perform one-to-many correlation query. 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)

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

PHP API Rate Limiting: Implementation strategies. PHP API Rate Limiting: Implementation strategies. Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

PHP Input Validation: Best practices. PHP Input Validation: Best practices. Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

See all articles