【问题标题】:Grab Table Name From MySQL Database Using PHP使用 PHP 从 MySQL 数据库中获取表名
【发布时间】:2017-08-10 10:25:10
【问题描述】:

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

[
 {
   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);
?>

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    输出数组的时候加上名字就行了:

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

    【讨论】:

    • 那行得通。太感谢了!我会在几分钟内接受你的答案是正确的
    猜你喜欢
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多