简体   繁体   English

PHP Foreach循环查询

[英]PHP Foreach Loop Query

I've been tinkering with PHP lately (self-taught, no formal training), trying to understand how to grab data from a database and display the data somewhere. 我最近一直在修改PHP(自学成才,没有接受过正式培训),试图了解如何从数据库中获取数据并在某处显示数据。 So far I have learned quite a bit, but now I am stumped. 到目前为止,我已经学到了很多东西,但是现在我很沮丧。

I have a list of about 200 users in my local database in a table called site_members. 我的本地数据库中有一个名为site_members的表,其中包含大约200个用户的列表。 The table has three fields: id, name, birth_date. 该表具有三个字段:id,name,birate_date。 Via PHP, I want to display all the users on a webpage, and have something like "Birthday soon!" 通过PHP,我想在网页上显示所有用户,并且显示类似“生日即将到来!”的信息。 be mentioned right after their name. 在他们的名字后面被提及。 Something like this: 像这样:

John Smith (Birthday soon!) 约翰·史密斯(即将出生!)

I haven't written the code to do this, because I usually write pseudocode first before actually diving into the coding part. 我没有编写代码来执行此操作,因为通常在实际进入编码部分之前,我会先编写伪代码。 Here's the pseudocode: 这是伪代码:

  • Get the current date and time and convert it to Unix timestamp 获取当前日期和时间并将其转换为Unix时间戳
  • Start foreach loop and go through list of users 开始foreach循环并浏览用户列表
    • Query the database table, get the birthdate of a user by their id, and store it in a variable named bdate. 查询数据库表,通过用户ID获取用户的生日,并将其存储在名为bdate的变量中。
    • Convert bdate to Unix timestamp 将bdate转换为Unix时间戳
    • Subtract the current date from bdate, convert it into days remaining, and store it in a variable called remaining_days. 从bdate中减去当前日期,将其转换为剩余天数,然后将其存储在名为剩余天数的变量中。
    • If the user's bdate is within 15 days (remaining_days is less than 15) 如果用户的约会日期在15天内(remaining_days少于15)
      • Display their name, followed by (Birthday soon!) 显示他们的名字,然后显示(生日不久!)
    • otherwise 除此以外
      • Just display their name only 只显示他们的名字
    • End if 万一
  • End foreach loop 结束foreach循环

Here's my problem: With the above pseudocode once translated into actual code, there would be a database query made every time in that foreach loop. 这是我的问题:将上述伪代码转换为实际代码后,每次在foreach循环中都会进行一次数据库查询。 Some of the tutorials I consulted mentioned I should avoid that for efficiency reasons, and it makes sense. 我参考的一些教程提到出于效率原因,我应该避免这种情况,这是有道理的。 I ran Google searches to find something similar, but that didn't do much. 我运行Google搜索来找到类似的内容,但是并没有太大的作用。 I do not want anyone to write any actual code for me. 我不希望任何人为我编写任何实际代码。 I just want a better solution to the querying. 我只是想为查询提供更好的解决方案。

Thanks in advance! 提前致谢!

I think your concept for the pseudo code is right, and you're understanding of doing multiple database queries is also right, you just tangled the two into giving you a wrong idea. 我认为您的伪代码概念是正确的,并且您了解执行多个数据库查询也是正确的,您只是将两者纠结在一起就得出了错误的想法。

If you construct your select statement properly (that's basically what you'd be using to access the database), you actually pull the information for everyone out of the database and store it once in an array (or some other form of object). 如果正确构造了select语句(基本上就是访问数据库所用的语句),则实际上会将所有人的信息从数据库中拉出,并将其一次存储在数组(或某种其他形式的对象)中。 You can then start your foreach loop using the array as your value and perform the rest of your checks that way. 然后,您可以使用数组作为值来启动foreach循环,并以这种方式执行其余的检查。

$date = date("m.d.y");
$people = ** insert your commands to grab the info from the DB **
foreach($people as $person) {
    // do your comparison checks and echo's etc in here
}

Does this make sense? 这有意义吗?

There can be two solutions to your problem:- 可以有两种解决问题的方法: -

1: 1:

Instead of making query for every user, first get the data for all the users. 与其查询每个用户,不如先获取所有用户的数据。
Traverse the data using foreach loop php 使用foreach循环遍历数据
Do the processing and display the results. 进行处理并显示结果。

2: 2:

Store the user date_of_birth in proper mysql date datatype 将用户date_of_birth存储在正确的mysql date数据类型中
Change your mysql query to use date function to get all the users who match your date difference criteria and just display those users. 更改您的mysql查询以使用date函数获取与您的日期差条件匹配的所有用户,并仅显示这些用户。

It seems you failed to read up properly on the relationship between SQL and PHP. 看来你没有在SQL和PHP之间的关系,正确读取了。 If you actually posted code, then you could have been easily unstumped because there are many ways to do the simple task from legacy tutorials to current PDO or even MVC within in 5mins or less. 如果您实际发布了代码,那么您可能会很容易陷入困境,因为有很多方法可以在5分钟或更短的时间内完成从旧教程到当前PDO甚至MVC的简单任务。

I'm not going to write the code but you need to change HOW you think in your "pseudo code". 我不会编写代码,但是您需要更改您在“伪代码”中的想法。

The problem with your pseudo code is because you believe that the DB is not smart and you are doing it as if it was only for storage. 伪代码的问题是因为您认为数据库不是很聪明,并且您正在执行该数据库,就好像它仅用于存储一样。

The correct pattern for PHP is the following: PHP的正确模式如下:

1) use the Date function to retrieve current day + 15. Get month and day only. 1)使用日期功能检索当前日期+15。仅获取月份和日期。

2) you make a SQL query that retrieve all users who's birth_date field's month and day are GREATER THAN (or equal) to TODAY and who are less than or equal to today + 15 (day and month only) 2)您执行一个SQL查询,检索所有birth_date字段的月和日大于或等于TODAY且小于或等于今天+ 15(仅日和月)的用户

3) execute the query. 3)执行查询。

4) with the returned data set (if any) you can choose two path depending situation and design 4)使用返回的数据集(如果有),您可以根据情况和设计选择两条路径

a) you can loop it with a simple FETCH which fetch each row retrieve and display name and extra message. a)您可以使用一个简单的FETCH来循环它,该FETCH可以获取每一行的内容并显示名称和其他消息。

or 要么

b) iterates through the result set and store the display message into a variable and then finally display it once the iteration is done. b)遍历结果集并将显示消息存储到变量中,然后在完成迭代后最终显示它。

(option b is prefered because its more flexible since you can use this technique to out into a file instead of an echo) (首选选项b是因为它更灵活,因为您可以使用此技术将其输出到文件中,而不是回显)

THIS pseudo-code ensures that you are only retrieve the correct data set with the aid of the SQL system (or storage system). 此伪代码可确保您仅在SQL系统(或存储系统)的帮助下检索正确的数据集。

In terms of overall process, aashnisshah is absolutely correct. 在整个过程方面, aashnisshah是绝对正确的。 First, you should retrieve all the records you need from your database then loop through each row to do your data comparisons and finally close the loop. 首先,您应该从数据库中检索所需的所有记录,然后循环浏览每一行以进行数据比较,最后关闭循环。

As for finding out if their birthday is close and if you want MySQL to do the hard work, you can build your query like that in PHP: 至于确定他们的生日是否临近,以及是否希望MySQL进行艰苦的工作,您可以像在PHP中那样构建查询:

$query = "SELECT *, DATEDIFF(DATE_FORMAT(dob, '" . date('Y') . "-%m-%d'), CURDATE()) AS days_to_dob FROM Members";

The idea is to fetch an extra column called 'days_to_dob' containing the amount of days until that person's date of birth. 想法是获取一个额外的列,称为“ days_to_dob”,其中包含该人的生日之前的天数。 Note that it will be negative if that date has passed for this year. 请注意,如果该日期已过今年,它将为负。 With that extra column you can easily evaluate whether their dob is within 15 days. 使用该额外的列,您可以轻松地评估他们的任务是否在15天内。

If you don't want any php code, then here is my pseudocode: 如果您不需要任何php代码,那么这是我的伪代码:

Get date  and time -> UTC stamp and store in $time_current
Get all from site_members and store in $data
for each entry in $data, store in $record
    get birth_date from $record and convert to utc stamp and store in $birthday
    print name from $record
    if $birthday is close to $time_current then print "Birthday soon" end if
    print new line
end for

That performs only one request to your database. 该操作仅对数据库执行一个请求。

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

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