简体   繁体   English

根据PHP中的结果运行第二个MySQL查询

[英]Run a second MySQL query based on results in PHP

EDIT: I've just thought I could run this as one query with something like this: 编辑:我只是想我可以作为这样的查询作为一个查询运行:

SELECT * FROM clubs
JOIN match_request_archive
ON (SELECT COUNT (clubs.id) AS requests FROM match_request_archive)

I appreciate though my syntax is horrendous I've just whipped this up and will tweak it now. 我很欣赏我的语法,虽然我的语法太可怕了,但我还是对其进行了整理,现在将对其进行调整。


I have a basic script for displaying data in a table. 我有一个用于在表中显示数据的基本脚本。 I've got a problem I can't solve which is I need to run one simple query to show all the data to the user. 我有一个我无法解决的问题,这是我需要运行一个简单的查询来向用户显示所有数据。 But in the last column I need to run a separate query to get the result. 但是在最后一列中,我需要运行一个单独的查询来获取结果。

Basically the first column in my table has the unique ID of a Rugby Club on the database. 基本上,表中的第一列在数据库上具有橄榄球俱乐部的唯一ID。 In a separate table on the database is a list of all requests made by clubs to players. 在数据库的另一个表格中,列出了俱乐部对球员的所有要求。 I want to display how many requests each club has made in the last column of my script below which means running this query: 我想在下面的脚本的最后一栏中显示每个俱乐部发出的请求数量,这意味着运行此查询:

SELECT * FROM match_request_archive WHERE club_id LIKE "$row['id']"

The $row['id'] is from the PHP script below: $ row ['id']来自下面的PHP脚本:

<?php
include 'credentials.php';

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM clubs";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc())

    {

        echo "
        <tr>
        <td>" . $row['id'] . "</td>
        <td>" . $row['club_name'] . "</td>
        <td>" . $row['club_captain'] . "</td>
        <td>" . $row['club_captain_number'] . "</td>
        <td>" . $row['club_captain_email'] . "</td>
        <td>TBC</td>
        </tr>
        ";
    }
} else {
    echo "<tr><td>0 results</td></tr>";
}
$conn->close();
?>

To solve this I tried embedding a second script in the echo command but it's my understanding you can't do this and in any case it did cause a fatal error. 为了解决这个问题,我尝试在echo命令中嵌入第二个脚本,但是据我了解,您不能执行此操作,无论如何它都会导致致命错误。 I can run this query separately and have it displayed in a different table, my problem is I need this to be all in one table. 我可以单独运行此查询,并将其显示在另一个表中,我的问题是我需要将此查询全部放在一个表中。 I hope that all makes sense. 我希望一切都有意义。

Executing query in loop is bad practice because it has very slow performance. 循环执行查询是一种不好的做法,因为它的性能非常慢。 So you should try get all data by one query if it possible: 因此,如果可能,您应该尝试通过一个查询获取所有数据:

SELECT *, COUNT(*) FROM clubs
LEFT JOIN match_request_archive
ON match_request_archive.club_id = clubs.id
GROUP BY clubs.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM