使用PHP从MySQL数据库中获取表名

时间:2017-08-10 10:25:10

标签: php mysql

我试图只抓取一个表名,以便包含表名来创建一个字典项数组。这就是我的表目前的样子:

[
 {
   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 个答案:

答案 0 :(得分:1)

输出数组时只需添加名称:

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