SQL请求不按预期工作

时间:2018-06-14 15:19:38

标签: php mysql sql rest

我有一个PHP REST API,我做了这个函数来获取具有某个idpro或idclient的服务

 function getServices($request) {
     require_once 'db.php';
     $emp = json_decode($request->getBody());
     $id = $request->getAttribute("id");
    $sql = "select * FROM service WHERE idpro=:idpro OR idclient= :idclient ORDER BY date_debut DESC";

    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("idpro", $id);
        $stmt->bindParam("idclient", $id);
         $stmt->execute();
        $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;

        return json_encode( $wines);

    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

当我使用idpro=40执行此函数时,我在我的数据库中有一行idclient=30id=40获得了不良结果,但当我用id=30执行时没有得到任何东西,我试图在PHPMYADMIN中执行这一行:select * FROM service WHERE idpro=30 OR idclient= 30并且它按预期工作

1 个答案:

答案 0 :(得分:0)

$sql = "select * FROM service WHERE idpro=:idpro OR idclient=:idclient ORDER BY date_debut DESC";

您提到它与idpro一起使用,并且参数和值之间没有空格,因此请尝试删除idclient= :idclient之间的空格以查看是否存在问题。因为它在你执行该行时有效,所以我假设它是如何在语法上调用的。

OR

尝试为该值使用一个参数。改变如下:

function getServices($request) {
     require_once 'db.php';
     $emp = json_decode($request->getBody());
     $id = $request->getAttribute("id");
    $sql = "select * FROM service WHERE idpro=:myID OR idclient= :myID ORDER BY date_debut DESC";

    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("myID", $id);
        $stmt->execute();
        $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;

        return json_encode( $wines);

    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}