2017-08-10 14 views
0

テーブル名を含めて辞書項目の配列を作成するために、1つのテーブル名を取得しようとしています。これは私のテーブルには、現在のように見えるものです:MySQLデータベースからテーブルを取得するPHPを使用する

[ 
{ 
    id: "1", 
    track: "Revolution", 
    artist: "Lou Yoellin", 
    file: "Revolution.mp3" 
}, 
{ 
    id: "2", 
    track: "Superstitious", 
    artist: "Random Artist", 
    file: "Superstitious.mp3" 
} 
] 

私は、配列の前に、歌を私のテーブルの名前を追加するために変更したい:

songs: [ 
{ 
    id: "1", 
    track: "Revolution", 
    artist: "Lou Yoellin", 
    file: "Revolution.mp3" 
}, 
{ 
    id: "2", 
    track: "Superstitious", 
    artist: "Random Artist", 
    file: "Superstitious.mp3" 
} 
] 

私は複数のテーブルを取得したくありませんただ一つ。以下は私のPHPコードです。私はSQLコマンドを変更する必要があると感じていますが、プログラミングとデータベースの取得はかなり新しいです。

$con=mysqli_connect("x","x","x","x"); 

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

// This SQL statement selects ALL from the table 'Songs' 
$sql = "SELECT * FROM songs"; 

// Show all Tables 
// $sql = "SHOW TABLES FROM myiosapp"; 

// $sql = "SELECT songs FROM myiosapp.tables"; 


// 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

あなたは出力配列だけで名前を追加します。

echo json_encode(['songs' => $resultArray]); 
+0

働いていました。どうもありがとうございます!あなたの答えを正しいものとして受け入れます – a2b123

関連する問題