doukoumi3389 2010-06-20 23:19
浏览 31
已采纳

如何返回具有特定字段值的所有数据库行

Hey, I have a database table called "projects" with the fields 'id', 'locationid', 'name' and 'year'. I query the database to retrieve all the values and store them in $data, before passing them into the relevant view.

In what part of the website, I have created a timeline (made of list items generated with a foreach). In this timeline, I was to associate projects with their corresponding 'year' value. So under 1999, I would find all the projects for 1999.

Right now I have an ugly hacked solution where inside the foreach which I use to generate the timeline I have ANOTHER foreach that goes through the projects table and checks to see if the 'year' field matches the current timeline year, and if so adds it.

Is there a more elegant way to query the $data I passed into the view (and therefore database field values) based on finding specific strings?

Essentially, if I could write it how I want to express it, I'm looking for something like this:

<?php foreach $year_range as $timeline_year : ?>
   <div class="projects_menu">
      <?php foreach $projects WHERE $projects->$year EQUAL $timeline_year : ?>
      <?php echo $projects->$name ?>
      <?php endforeach ?>
   </div>
<?php endforeach ?>
  • 写回答

3条回答 默认 最新

  • douzhuanfen5923 2010-06-21 02:00
    关注

    I may be misunderstanding the question, but it seems like you could do something like:

    SELECT * FROM projects WHERE ($condition) ORDER BY YEAR ASC, name ASC
    

    And then simply output the results in PHP:

    foreach ($projects as $project) {
        /* output $project */
    }
    

    or

    foreach ($year_range as $year) {
        /* output timeline, inserting projects if any occur in that year */
    }
    

    $condition might be something like:

    projects.year >= $start_year AND projects.year <= $end_year
    

    or

    projects.year IN ($year_range)
    

    or

    projects.year IN ($year_range) and project.name LIKE '%$search_string%'
    

    You'll have to be more specific about "finding specific strings" as I'm not sure where that would come into play in this problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏