2017-04-18 203 views
0

我有下面的PHP腳本生成一個MySQL查詢並運行它,但是目前查詢返回一個空結果。PDO返回空結果

$sth = $dbh->prepare("SELECT TeamID FROM UserTeam WHERE UserID=? AND Deleted IS NULL"); 
      $sth->execute(array($_POST['userID'])); 
      $teams = $sth->fetchAll(); 

      $sql = "SELECT * FROM Event WHERE UserID=? AND Deleted IS NULL"; 

      if (count($teams) > 0) { 
       $sql .= " OR TeamID IN ("; 
       foreach ($teams as $team){ 
        $sql .= $team['TeamID'] . ","; 
       } 

       $sql = substr($sql, 0, -1); 

       $sql .= ")"; 
      } 

      $sql .= " ORDER BY Created DESC LIMIT ?, 10 "; 

      $sth = $dbh->prepare($sql); 
      $sth->execute(array($_POST['userID'], $_POST['start'])); 
      $events = $sth->fetchAll(); 

      $response["success"] = 1; 
      $response["result"] = $events; 
      $response["sql"] = $sql; 
      $response["post"] = $_POST; 
      echo json_encode($response); 

是例如給輸出JSON陣列:

{ 
    "post" : { 
    "start" : "0", 
    "userID" : "33" 
    }, 
    "result" : [ 

    ], 
    "sql" : "SELECT * FROM Event WHERE UserID=? AND Deleted IS NULL OR TeamID IN (12,13,17) ORDER BY Created DESC LIMIT ?, 10 ", 
    "success" : 1 
} 

但是,如果我運行生成的查詢(?用正確的值替換)對數據庫手動我得到預期的結果( 10個返回結果)

更新

即使在更改SQL代硬編碼值 代替 ?我仍然沒有結果。

{ 
    "post" : { 
    "start" : "0", 
    "userID" : "33" 
    }, 
    "result" : [ 

    ], 
    "sql" : "SELECT * FROM Event WHERE UserID=33 AND Deleted IS NULL OR TeamID IN (12,13,17) ORDER BY Created DESC LIMIT 0, 10 ", 
    "success" : 1 
} 
+1

試圖通過一個變量,而不是'$ _ POST [「用戶ID」]',你也可以通過你的連接'$ dbh->的setAttribute(PDO :: ATTR_ERRMODE,PDO後添加此啓用錯誤方式: :ERRMODE_EXCEPTION);' –

+0

直接在數據庫中運行查詢以查看是否出現錯誤。 – TurtleTread

+0

已經說過它對數據庫正確工作 –

回答

0

你不能在LIMIT子句中使用的佔位符。你也不需要,因爲它是一個很容易安全的整數。另外,您可以從第一個查詢中獲取列,以更輕鬆地構建第二個查詢。我懷疑這可能會被一個單一的查詢獲取,但不能確定沒有看到你的數據庫模式。

最後,你沒有捕捉到你的數據庫代碼中的任何錯誤,所以你不知道是否有什麼會成功。假設你正確地建立了連接,你應該能夠捕捉到任何異常。

<?php 
try { 
    $sth = $dbh->prepare("SELECT TeamID FROM UserTeam WHERE UserID=? AND Deleted IS NULL"); 
    $sth->execute([$_POST["userID"]]); 
    $teams = $sth->fetchAll(PDO::FETCH_COLUMN, 0); 
} catch (PDOException $e) { 
    // do something here 
} 
$start = (int)$_POST["start"]; 

$sql = "SELECT * FROM Event WHERE UserID=? AND Deleted IS NULL"; 

if (count($teams) > 0) { 
    $sql .= " OR TeamID IN (" . implode(",", $teams) . ")"; 
} 

$sql .= " ORDER BY Created DESC LIMIT $start, 10"; 

try { 
    $sth = $dbh->prepare($sql); 
    $sth->execute([$_POST["userID"]]); 
    $events = $sth->fetchAll(); 
} catch (PDOException $e) { 
    // do something here 
} 
$response["success"] = 1; 
$response["result"] = $events; 
$response["sql"] = $sql; 
$response["post"] = $_POST; 
header("Content-Type: application/json"); 
echo json_encode($response); 
0

嘗試添加括號到SQL查詢。例如,而不是:

SELECT * FROM Event WHERE UserID=33 AND Deleted IS NULL OR TeamID IN (12,13,17) ORDER BY Created DESC LIMIT 0, 10 

嘗試:

SELECT * FROM Event WHERE UserID=33 AND (Deleted IS NULL OR TeamID IN (12,13,17)) ORDER BY Created DESC LIMIT 0, 10