-1

我有一个名为“main_table”的表,包含 3 列:
“player”、“points”和“drop_date”

我有 1 个具有不同值的变量 ($date):

$date == '2012-06-01'  
$date == '2012-05-01'  
$date == '2012-04-01'  

我有 1 个 MySQL 查询:

$query = "
  select *
  from main_table
  where `drop_date` > '$date'
    AND `drop_date` <= DATE_ADD('$date', INTERVAL 1 YEAR)
  LIMIT 1
";

目标:
我想用不同的pass运行一个查询(每个值1pass)

我努力了 :

<?php
$date['date'] = '2012-06-01';  
$date['date'] = '2012-05-01'; 
$date['date'] = '2012-04-01';

foreach($date as $title => $actual_date) {
  query = "
    select *
    from main_table
    where `drop_date` > '$actual_date'
      AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR)
    LIMIT 1
  ";
  $result = mysql_query($query) or die(mysql_error());
}

while($row = mysql_fetch_array($result)) {
  echo $row['Player'];
  echo $row['Points'];
}
4

3 回答 3

3

您一遍又一遍地覆盖相同的变量......然后您运行查询但只获取最后一个的结果。你期望它如何工作?

尝试这个:

$date = Array("2012-06-01","2012-05-01","2012-04-02");
foreach($date as $actual_date) {
    if( $result = mysql_fetch_assoc(mysql_query("select * from `main_table` where `drop_date`>'".$actual_date."' and `drop_date`<=date_add('".$actual_date."',interval 1 year) limit 1"))) {
        echo $result['Player'];
        echo $result['Points'];
    }
}

请注意,我跳过了将查询放入变量中,并将查询结果放入变量中,而只是将整个内容放在一行中。由于您limit 1的查询将仅返回一行,因此无需while循环它。

于 2012-06-22T16:17:17.150 回答
1

只需在 foreach 循环中移动你的 while。

<?php
$date[0] = '2012-06-01';  
$date[1] = '2012-05-01'; 
$date[2] = '2012-04-01';
foreach($date as $title => $actual_date)
{
    query = "select * from main_table where `drop_date` > '$actual_date' AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR) LIMIT 1"; 
    $result = mysql_query($query) or die(mysql_error());

    while($row = mysql_fetch_array($result))
    {
        echo $row['Player'];
        echo $row['Points'];
    }
}
于 2012-06-22T16:16:28.367 回答
1

不要覆盖您的值。这样做可以保留所有 3 个值。

<?php 
$date['date'][] = '2012-06-01';  
$date['date'][] = '2012-05-01'; 
$date['date'][] = '2012-04-01';

print_r($date);
?>

输出:

Array
(
    [date] => Array
        (
            [0] => 2012-06-01
            [1] => 2012-05-01
            [2] => 2012-04-01
        )

)

然后使用

foreach ($date['date'] as $actual_date) {

 $query = "
   select *
   from main_table
   where `drop_date` > '$actual_date'
     AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR)
   LIMIT 1";

   echo $query."<br />";

}

输出:

select *
    from main_table
    where `drop_date` > '2012-06-01'
      AND `drop_date` <= DATE_ADD('2012-06-01', INTERVAL 1 YEAR)
    LIMIT 1
  <br />
    select *
    from main_table
    where `drop_date` > '2012-05-01'
      AND `drop_date` <= DATE_ADD('2012-05-01', INTERVAL 1 YEAR)
    LIMIT 1
  <br />
    select *
    from main_table
    where `drop_date` > '2012-04-01'
      AND `drop_date` <= DATE_ADD('2012-04-01', INTERVAL 1 YEAR)
    LIMIT 1
  <br />
于 2012-06-22T16:21:29.637 回答