我正在尝试用给定的日期替换查询中的所有%s。但这使我感到困惑,并且在Date_format.处出现错误%s中的fcst_date被正确替换。请帮忙

    $day1 = date('Y-m-d');
    $day2 = date('Y-m-d', strtotime("+1 days"));
    $day3 = date('Y-m-d', strtotime("+2 days"));
    $day4 = date('Y-m-d', strtotime("+3 days"));
    $day5 = date('Y-m-d', strtotime("+4 days"));
    $day6 = date('Y-m-d', strtotime("+5 days"));
    $day7 = date('Y-m-d', strtotime("+6 days"));
    $day8 = date('Y-m-d', strtotime("+7 days"));
    $day9 = date('Y-m-d', strtotime("+8 days"));
    $day10 = date('Y-m-d', strtotime("+9 days"));
    $query = sprintf('SELECT blk_id,blk_name,fcst_date,temp_max,max_temp,date,temp_stn_block.stn_id FROM temp_stn_block RIGHT JOIN temp_stn_normals ON temp_stn_block.stn_id=temp_stn_normals.stn_id INNER JOIN block_imd_gfs_forecast ON blk_id=block_id JOIN block_s ON block_s.id=blk_id WHERE DATE_FORMAT(date, "%%m-%%d") IN DATE_FORMAT("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s", "%%m-%%d") AND fcst_date IN (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", $day1, $day2, $day3, $day4,$day5, $day6, $day7,$day8,$day9,$day10, $day1, $day2, $day3, $day4,$day5, $day6, $day7,$day8,$day9,$day10);
    $res = $this->db->query($query);
    return $res->result();

最佳答案

我宁愿使用准备好的带有命名参数的语句来实现此目的,只是为了获得更易读的代码。但是随后您将不得不更新您的codeigniter db配置以使用PDO驱动程序。

对于sprintf,仅使用编号的占位符:


$qry_str = 'SELECT
 blk_id,blk_name,fcst_date,temp_max,max_temp,date,temp_stn_block.stn_id
 FROM temp_stn_block
 RIGHT JOIN temp_stn_normals
   ON temp_stn_block.stn_id=temp_stn_normals.stn_id
 INNER JOIN block_imd_gfs_forecast
   ON blk_id=block_id JOIN block_s ON block_s.id=blk_id
 WHERE
   DATE_FORMAT(date, "%%m-%%d") BETWEEN *day1* AND *day10*
 AND
   fcst_date IN (%1$s, %2$s, %3$s, %4$s, %5$s, %6$s, %7$s, %8$s, %9$s, %10$s)"
';

$query = sprintf($qry_str, $day1, $day2, $day3, $day4, $day5, $day6, $day7, $day8, $day9, $day10);

$res = $this->db->query($query);



我认为查询的问题是%s的用法,它是DATE_FORMAT中“秒”的说明符

关于php - 如何用date_format替换sprintf中的多个%s?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54530137/

10-10 19:02
查看更多