2016-06-23 19 views
0

如何在while循環中添加多個值,我只能根據我的級別添加兩個值,一個是id,另一個是標題,我想添加更像是我的字段是從服務器獲取請幫助任何人如何在PHP中while循環中從數組中調用多個值

$limitStart = $_POST['limitStart']; 
    $limitCount = 15; 
    if(isset($limitStart) || !empty($limitstart)) { 
     $con = mysqli_connect($hostname, $username, $password, $dbname); 
     $query = 'SELECT id, title, caption, description, featured_image, logo, category_sku, industry_sku 
       FROM works ORDER BY title limit '.$limitStart.','.$limitCount .''; 
     $result = mysqli_query($con, $query); 
     $res = array(); 
     while ($resultSet = mysqli_fetch_assoc($result)) { 
     $res[$resultSet['id']] = $resultSet['featured_image']; 
     } 
     echo json_encode($res); 
    } 

回答

0

只是他們都添加爲$resultSet已經是一個關聯數組:

while ($resultSet = mysqli_fetch_assoc($result)) { 
    $id = $resultSet['id']; 
    unset($resultSet['id']); // <-- add this is if you don't want the id in the final set as it's now the key. 
    $res[$id] = $resultSet; 
} 

或者挑選擇某些字段,只需做一些基本的PHP,將additinonal字段添加爲新的關聯數組。

下面是與添加captionfeatured_image一個例子:

while ($resultSet = mysqli_fetch_assoc($result)) { 
    $res[$resultSet['id']] = ['featured_image'=>$resultSet['featured_image'], 
           'caption' => $resultSet['caption']]; 
    } 
0

也許是這樣的:

$res = array(); 
while ($resultSet = mysqli_fetch_assoc($result)) { 
    foreach($resultSet as $key => $value) { 
     $res[$key] = $value; 
    } 
} 

會做的伎倆?

+0

只獲取一個Id相關的數據,還有其他很多的id。 –

+0

您可以發佈數據存儲結構嗎? –

0

如果您的$ limitStart是14,您的$ limitCount是15,它應該返回一個ID。

$limitStart = $_POST['limitStart']; // What is this number? 
$limitCount = 15; 

您的if語句中存在拼寫錯誤,請參見下文。

此外,由於您沒有準備好您的語句,因此您的代碼易受SQL注入影響。

if(isset($limitStart) || !empty($limitStart)) { // Typo here. (small s) 

    $mysqli = mysqli_connect($hostname, $username, $password, $dbname); 

    $sql = "SELECT id, title, caption, description, featured_image, logo, category_sku, industry_sku 
     FROM works ORDER BY title limit ".$limitStart.",".$limitCount.""; 

    $stmt = $mysqli->prepare($sql); // Prepare the statement 
    $stmt->bind_param("ii", $limitStart, $limitCount); // Bind the parameters 
    $stmt->execute(); // Execute the query 

    // Bind the result 
    $stmt->bind_result($id, $title, $caption, $description, $featured_image, $logo, $category_sku, $industry_sku); 
    $result = $stmt->get_result(); 
    $res = array(); 

    while ($resultSet = $result->fetch_assoc()) { 
     $res[$resultSet['id']] = $id; 
    } 

    $stmt->close(); // Close the statement 
    $mysqli->close(); 

    echo json_encode($res); 

}