mysql select查询在phpmyadmin上运行正常,但不与php一起运行

时间:2018-11-24 15:56:31

标签: php mysql sql database

这是mysql查询

SELECT *,
    `main`.`email` as useremail,
    `main`.`ID` as `userID`,
    `mail_owners`.`country_code_field` as `micountry`,
    DATE(`main`.`time`) as `mrDate`
FROM `main`
LEFT JOIN `mail_owners`
    ON `main`.`ID` = `mail_owners`.`ID`
WHERE
    `main`.`is_deleted` = 0 AND
   (`main`.`time` BETWEEN '2018-08-01' AND '2018-11-14')
ORDER BY
   `main`.`ID`,
    `mrDate` DESC

此查询在sql上可以正常运行。...但是在php上不能正常运行。 它在php上运行,但只获取一些数据而不是总数。

此处描述了php代码:

$fdt = $_POST['formDt'];
$tdt = $_POST['toDate'];

$sqlforData = "SELECT *, `main`.`email` as useremail, `main`.`ID` as `userID`, `mail_owners`.`country_code_field` as `micountry`, DATE(`main`.`time`) as `mrDate` FROM `main` LEFT JOIN `mail_owners` ON `main`.`ID` = `mail_owners`.`ID` WHERE `main`.`is_deleted` = 0 AND (`main`.`time` BETWEEN '$fdt' AND '$tdt') ORDER BY `main`.`ID`, `mrDate` DESC";

$result = mysqli_query($conn, $sqlforData);
while ($table = mysqli_fetch_array($result)) {
  //Showing just limited data...
}

请帮助我解决问题。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可能会遇到一些报价和转换问题,请尝试使用str_to_date来避免sqlinject和转换问题,以尝试使用已准备好的语句和绑定参数,例如:

    $sqlforData = "SELECT *
        , `main`.`email` as useremail
        , `main`.`ID` as `userID`
        , `mail_owners`.`country_code_field` as `micountry`
        , DATE(`main`.`time`) as `mrDate` 
    FROM `main` 
    LEFT JOIN `mail_owners` ON `main`.`ID` = `mail_owners`.`ID` 
    WHERE `main`.`is_deleted` = 0 AND (`main`.`time` BETWEEN STR_TO_DATE(?, '%Y-%m%d')  
                        AND STR_TO_DATE(?, '%Y-%m%d')) 
    ORDER BY `main`.`ID`, `mrDate` DESC";


    $stmt = $mysqli->prepare($sqlforData);
    $stmt->bind_param('ss', $fdt, $tdt, );

    $stmt->execute();