2016-05-26 5 views
0

単一の列からデータを取得してAPI(Json)に入れる必要がありますが、何らかの理由で列のタイトルも取得する必要があります。単一の列の値を取得する

$sql = "SELECT workingJson FROM dataTable"; 

私はそれがworkingJson.Valueが、運のようになると想定。ここで

あなたのコメントあたりAPI.php

// Create connection 
$con=mysqli_connect("localhost","user","password","database"); 

// Check connection 
if (mysqli_connect_errno()) 
{ 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

// This SQL statement selects ALL from the table 'Locations' 
$sql = "SELECT column1 FROM database"; 

// Check if there are results 
if ($result = mysqli_query($con, $sql)) 
{ 
    // If so, then create a results array and a temporary one 
    // to hold the data 
    $resultArray = array(); 
    $tempArray = array(); 

    // Loop through each row in the result set 
    while($row = $result->fetch_object()) 
    { 
     // Add each row into our results array 
     $tempArray = $row; 
     array_push($resultArray, $tempArray); 
    } 

    // Finally, encode the array to JSON and output the results 
    echo json_encode($resultArray); 
} 

// Close connections 
mysqli_close($con); 

答えて

1

編集です:

は単なる値ではなくPHPのキーを返すために、あなたはこのようにコードを変更することができます:

// Loop through each row in the result set 
while($row = $result->fetch_object()) 
{ 
    // Add value to array 
    array_push($resultArray, $row->column1); 
} 

この場合、$tempArrayの必要はありません。

+0

@WillemMassoelsを。 –

+0

私は運が怖いです、とにかくマイクありがとう! –

+0

@WillemMassoels私は、より多くのデバッグ情報を提供する必要があると思います。私が示したことは、 '[" somevalue "、" someothervalue "、...]'のようなJSON表現を返すでしょう。サーバーサイドまたはクライアントサイドのコード実行で、実行が期待どおりに異なる場所はどこですか? –

0

あなたはすべての結果とtraitmentをやった後得ることができます:私はあなたのコメントごとに私の答えを編集した

<?php 

// Create connection 
$con=mysqli_connect("localhost","user","password","database"); 

// Check connection 
if (mysqli_connect_errno()) 
{ 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

// This SQL statement selects ALL from the table 'Locations' 
$sql = "SELECT column1 FROM database"; 


if ($result = $mysqli->query($sql)) { 

    //get all fields : 
    $finfo = $result->fetch_fields(); 

    foreach ($finfo as $val) { 
     $resultArray[] = $val->column1; 
    } 
    $result->close(); 
} 

// Finally, output the results without encode because is also in json format: 
echo '{'. implode(','.chr(10), $resultArray) .'}'; 

$mysqli->close(); 
+0

ありがとうIlyas、エコー($ resultArray)です。 $ mysqli-> close();正しい構文は、配列をプレーンテキストでエコーします...現時点では、結果として「配列」を取得します。 –

+0

うん、私はこれを忘れて、今すぐ腹腔内にしよう! – Mimouni

+0

ありがとうございました。 –

関連する問題