2017-08-10 83 views
0

我想抓住一个表名,以便包含表名以创建一个字典项目数组。这是我的表目前是这样的:从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