简体   繁体   English

PHP的MySQL foreach循环

[英]php foreach loop with mysql

I am trying to retrieve data from my database. 我正在尝试从数据库中检索数据。 I need three pieces of data: kaupunki_id, Opisto and pisteet_1. 我需要三个数据:kaupunki_id,Opisto和pisteet_1。 The problem is that they all are in different tables. 问题在于它们都在不同的表中。 My code does retrieve the right data but it's not super automatic. 我的代码确实检索了正确的数据,但是它不是超级自动的。 At the moment the variable $t decides which data to pick. 目前,变量$ t决定要选择的数据。

My table structure: 我的表结构:

Table name: pisteet 表名: pisteet

在此处输入图片说明

Table name: oppilaitokset 表名: oppilaitokset

在此处输入图片说明

Table name: kaupungit 表名: kaupungit

在此处输入图片说明

What i need: For each opisto(row) i need to get the matching pisteet_1(row) and count the average of the points. 我需要什么:对于每个opisto(行),我需要获取匹配的pisteet_1(行)并计算点的平均值。 and then echo it in a <td> with the matching kaupunki_id(row) class. 然后使用匹配的kaupunki_id(row)类在<td>回显它。

In the table oppilaitokset there can be multiple rows that have the same kaupinki_id(row) ID. oppilaitokset表中 ,可以有多行具有相同的kaupinki_id(row) ID。

My code that is working but is only showing one result and its not not so automatic: 我的代码正在运行,但仅显示一个结果,但不是那么自动:

$keskiynnays = 0;
$kerto=0;
foreach ($db->query("SELECT kaupunki_id FROM pisteet") as $kaupunki_id) {
    foreach ($kaupunki_id as $kaikkinimet => $t) {
        $t= 1;
        foreach ($db->query("SELECT opisto FROM oppilaitokset WHERE kaupunki_id = '$t'") as $kaupungit) {
            foreach ($kaupungit as $kaupunki => $k) {
            }
        }
        foreach ($db->query("SELECT pisteet_1 FROM pisteet WHERE opisto_id = '$t'") as $keskiarvo1) {
            foreach ($keskiarvo1 as $loopkeskiarvo1 => $kes1) {
            }
            $kerto++;
            $keskiynnays +=$kes1;
            $keskiarvolaskettu1 = $keskiynnays / $kerto;
        }
    }       
}
echo "<td class=\"" . $t . "\">" . $k  . ": " . $keskiarvolaskettu1 . "</td>";

You are setting variable $t = 1 and that is why you are getting always the same row. 您正在设置变量$t = 1 ,这就是为什么总是得到同一行的原因。

Generally speaking, your code is terrible and you're running lots of queries. 一般来说,您的代码很糟糕,并且您正在运行大量查询。 Try googling about SQL JOINS to see how you can achieve the same results way faster. 尝试搜索有关SQL JOINS的信息,以了解如何更快地实现相同的结果。

As mentioned I would try a SQL join - something like this: 如前所述,我将尝试进行SQL连接-像这样:

$query = "SELECT opisto As O, AVG(pisteet_1) As P, ka.kaupunki_id As K FROM ".
"oppilaitokset op ".
"LEFT JOIN pisteet pi ".
"ON op.id = pi.opisto_id ".
"LEFT JOIN kaupungit ka ".
"ON op.kaupunki_id = ka.kaupunki_id ".
"GROUP BY opisto, ka.kaupunki_id";

foreach ($db->query($query) as $row) {
    print $row['O'] . "<br>";
    print $row['P'] . "<br>";
    print $row['K'] . "<br>";
}

So, you got pisteet Table, related to the others, by using foreign keys. 因此,通过使用外键,您获得了与其他表相关的pisteet表。 Okay. 好的。 Nice thing you uploaded these pictures. 很高兴您上传了这些图片。

If the database was not related, you should had to work like the way you do. 如果数据库不相关,则应该像以前那样工作。 It would be a terrible thing for a bunch of reasons. 出于多种原因,这将是一件可怕的事情。 But that's why SQL was invented for. 但这就是为什么要发明SQL的原因。 A Relational Database System MUST be used at its full potential. 必须充分利用关系数据库系统。 You make your life hard anyway though. 无论如何,你都会使生活变得艰难。

You said: 你说:

"@Carpetsmoker Ye i know i'm sorry for that I had already so many and could not really change them anymore. :/ – " “ @Carpetsmoker是的,我知道我为此感到抱歉,因为我已经很多了,不能再真正改变它们了。:/ –”

Yes you can "do the job" using PHP and queries with no Join, BUT you must think of it. 是的,您可以使用PHP来“完成任务”,并且无需加入联接即可进行查询,但是您必须考虑一下。 Why did @Carpetsmoker told you that? 为什么@Carpetsmoker告诉你了?

" I had already so many and could not really change them anymore" makes me feel like you don't understand what you have put yourself into, but most important, what you insist keeping yourself into. “我已经有那么多了,不能再真正改变它们了”,使我感到您不了解自己的投入,但最重要的是,您坚持要坚持自己的投入。

Let's say you fixed the problem on this piece of code. 假设您已在此代码段上解决了该问题。 Next thing is reproducing code wrongly done everywhere on your project. 接下来的事情是在项目的任何地方都错误地复制代码。 How will you do that? 你会怎么做? Copy - paste and edit to fit your needs maybe? 复制-粘贴并编辑以适合您的需求?

It is 100% best practice to take some time, learn JOIN commands and what they do, then gradually remake queries using Joins. 花费一些时间,学习JOIN命令及其作用,然后使用Joins逐步重新进行查询,这是100%的最佳实践。 At LEAST PHP will do the job it was meant to do and MySQL will do the quering. PHP至少会完成原定的工作,而MySQL将进行查询。

As for the "there are too many" part, well, I trust you already know the concept of modular structured programming. 至于“太多”部分,我相信您已经知道模块化结构化编程的概念。

In case you do not, or you forgot, here is an example. 如果您不这样做或忘记了,请举一个例子。 Imagine you wanna do something, in 10 places on your code. 假设您想在代码的10个地方执行某些操作。 What do you do? 你是做什么?

1] You write the code and then copy paste it, slightly editing it to fit your needs. 1]编写代码,然后复制粘贴,然后根据需要进行略微编辑。

2] You make a function that contains the code, then call the function on these ten parts. 2]创建一个包含代码的函数,然后在这十个部分上调用该函数。 The editing could be implemented as a few arguments passed. 可以通过传递一些参数来实现编辑。

Approach 1] IS WRONG . 方法1] 错误

Approach 2] is a better way to do it. 方法2]是一种更好的方法。 Maybe not the best, but a better for sure. 也许不是最好的,但是可以肯定是更好的。 Can you imagine why? 你能想象为什么吗?

In the second approach, if you make a mistake, you change a function ONCE and it is changed for all ten places automaticaly. 在第二种方法中,如果您犯了一个错误,则可以更改一次功能,并且自动为所有十个位置更改该功能。 In the first approach, copy paste is your nemesis. 在第一种方法中,复制粘贴是您的宿敌。 You are already fed up with it. 您已经受够了。 Your own words say so: "you could not change them ANYMORE". 您自己的话是这样说的:“您无法再更改它们”。 Trust me on my first steps on programming I did worse mistakes than you. 相信我,在编程的第一步中,我犯的错误比你还糟。 And I was not fortunate to have Internet back then. 那时我还很幸运能够上网。 :( :(

So, a bad practice, can be easier to do in the begining (since you don't have to study a few concepts) but that doesn't make it easy in the long run. 因此,不好的做法从一开始就很容易做到(因为您不必学习一些概念),但是从长远来看,这并不容易。 You unfortunately learned that the hard way here. 不幸的是,您在这里学到了很难的方法。

Check out the following links for a quick understanding: Click here and Here 查看以下链接以快速了解: 单击此处此处

(a few first google search results) (一些最初的Google搜索结果)

You can thank us all later. 您可以稍后再感谢我们。

As for functions, start from here 至于功能,从这里开始

Combining these concepts, you will make your life easier for yourself. 结合这些概念,您将使自己的生活更轻松。

Finally, I assume you do not know these concepts. 最后,我假设您不了解这些概念。 I have no intention to offend you or make you feel bad. 我无意冒犯您或让您感到难过。 What I see is just a piece of code. 我看到的只是一段代码。

Cheers. 干杯。

Edit: Typos. 编辑:错别字。

This retrieves all the values and prints them correctly. 这将检索所有值并正确打印它们。 Modify code of @Kez (see above) 修改@Kez的代码(请参见上文)

echo "<table class=\"zebra1\">";
    echo "<tr>";
    $query = "SELECT opisto As O, AVG(pisteet_1) As P, ka.kaupunki_id As K FROM ".
    "oppilaitokset op ".
    "LEFT JOIN pisteet pi ".
    "ON op.opisto_id = pi.opisto_id ".
    "LEFT JOIN kaupungit ka ".
    "ON op.kaupunki_id = ka.kaupunki_id ".
    "GROUP BY opisto, ka.kaupunki_id";

    foreach ($db->query($query) as $row) {
        echo "<td class=\"" . $row['K'] . "\">" . $row['O'] . ": ";
        echo $row['P'] . "</td>";
    }
    echo "</tr>";
    echo '</table>';

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

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