2014-02-07 107 views
-2

我是neubie和PHP。我需要建立一些Web服務,所以我有問題..請幫助我。選擇記錄到陣列

我有這個代碼,我必須在數組中選擇的記錄和返回在JSON中。

代碼...

function redeem() { 
// Check for required parameters 
if (isset($_POST["id_cliente"]) && isset($_POST["id_sucursal"])) { 
    // Put parameters into local variables 
    $cliente = $_POST["id_cliente"]; 
    $sucursal = $_POST["id_sucursal"]; 
    $stmt = $this->db->prepare('SELECT id_arbitro FROM arbitro WHERE id_cliente =? AND id_sucursal =?') or die(mysqli_error($this->db)); 
    $stmt->bind_param("ii", $cliente, $sucursal); 
    $stmt->execute(); 
    //$stmt->bind_result($id_arbitro); 
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 
     $cuantos = count($result); 
    echo "$cuantos"; 

    $registros = 0; 
    /*while ($stmt->fetch()) {      
     $registros ++; 
     // Return unlock code, encoded with JSON 
     $result = array("id_arbitro" => $stmt,); 
     echo "$id_arbitro !"; 
    } 
    */ 
    $stmt->close(); 
    if ($registros < 0) { 
     sendResponse(400,"No existen arbitros con los parámetros recibidos"); 
     return false; 
    } 

    //echo json_encode($result); 
    sendResponse(200, "FIN"); 
    //printf("ERROR %s",$registros); 
    return true; 
} 
sendResponse(400, 'Invalid request'); 
return false; 

}

+0

那你哪個部位有麻煩?我們不能看到'$ this-> db'類的語法,但實質上需要迭代結果,將它們放入一個數組中,然後json_encode();它 – helion3

+0

嗨Helion。 SELECT instruccion它是很好的作品..如果我取消註釋的WHILE instuction,我可以在$ registros變量中獲得值,但我不能把記錄放在數組中... $ result = array(「id_arbitro」=> $ stmt, );當我試圖得到de count數組的項目時,我只得到一個記錄數($ result),這是我的問題 – user3285457

+0

我已根據此信息回答。 – helion3

回答

0

要編碼您的查詢的結果,使用類似的東西

$statement=$pdo->prepare("SELECT * FROM table"); 
$statement->execute(); 
$results=$statement->fetchAll(PDO::FETCH_ASSOC); 
$json=json_encode($results); 
+0

如何檢查$結果是否包含我的所有記錄以及計數($結果)? ...因爲最後doesen't工作 – user3285457

+0

是的,你應該能夠做sizeof($結果)或計數($結果)。 如果你想返回你的JSON計數,只要這樣做: return json_encode(array('Result'=> $ results,'count'=> sizeof($ results)); – user1168095

0

基於您的評論,您遇到問題了解如何將它們全部放入數組中。

首先,確保您用於數據庫調用的任何功能都沒有fetchAll樣式函數,可以爲您執行此操作。

如果您仍然需要做的,你需要首先定義一個數組,然後添加到它:

$results = array(); 
while ($record = $stmt->fetch()) {      
    $registros ++; 
    $results[] = $record; 
} 
print json_encode($results); 

的語法可能會爲你的數據庫類略有不同,但是這給你的想法。

+0

我怎麼能再次把我的代碼? – user3285457

+0

我提供了一個循環的例子,但您需要查看您正在使用的數據庫訪問類的文檔。 – helion3

+0

我使用Mysql。$ this-> db = new mysqli('localhost',' futchoco','Futcho19','futchoco_futsoft'); – user3285457