2015-06-19 64 views
1

我有一個數據庫,其中我有user_id & associated_id。單個user_id可以有多個associated_id。現在我想將所有associated_id s取到一個數組中。我已經嘗試過這種方法,但不知道如何讓它們在數組中。如何使用php中的準備語句從數據庫中獲取數據?

$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?"); 
$stmt->bind_param("s", $user_id); 
if ($stmt->execute()) 
    { 
     while ($stmt->fetch()) 
     { 
      //what to write here 

     } 


     //echo var_dump($user); 
     $stmt->close(); 

    } 
+0

您是否嘗試過Google? http://php.net/manual/de/pdostatement.fetch.php – Jens

回答

1

嘗試這種情況:

 $stmt = $mysqli->prepare("SELECT associated_id FROM my_contacts WHERE user_id = ?")) { 
     $stmt->bind_param('s', $user_id); // Bind "$user_id" to parameter. 
     $stmt->execute(); // Execute the prepared query. 
     $stmt->store_result(); 

     // get variables from result. 
     $stmt->bind_result($associated_id); 
     $stmt->fetch(); 

結果將被存儲在$associated_id陣列英寸

+0

我如何獲取元素數組 – Techiee

+0

'$ assosiated_id'是你的數組。 –

0

可以綁定像這樣的參數和使用方法fetchall讓所有的結果陣列

$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = :user_id"); 
$stmt->bind_param(":user_id", $user_id, PDO::PARAM_INT); 
if ($stmt->execute()) 
    { 
     $result = $stmt->fetchall(PDO::FETCH_ASSOC); 
     //echo var_dump($user); 
     $stmt->close(); 

    } 
+0

請建議與我的代碼相關的內容。我不明白PDO&all – Techiee

0

在根據你的代碼中使用的mysqli。

$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?"); 
if($stmt->execute()){ 
    $result = $stmt->get_result(); 
    if($result->nom_rows > 0){ 
    while($row = $result->fetch_assoc()){ 
     var_dump($row) 
    } 
    }else{ 
    echo "Sorry NO data found"; 
    } 
}else{ 
    echo "Some thing is wrong"; 
} 

這裏,你可以不使用$stmt->bind_result();而不是使用$stmt->get_result()

$stmt->bind_result();當您在選擇查詢定義字段僅用於

與*您需要使用$stmt->get_result()

請參閱本鏈接更多信息

Example of how to use bind_result vs get_result

相關問題