2016-05-13 87 views
2

我在PHP/MySQL中的經驗非常少。使用phpMyAdmin從MySQL獲取數據

我試圖通過phpMyAdmin從MySQL獲取數據,並將其返回到xcode格式,它可以理解。

<?php 

// Create connection 
$con=mysqli_connect("localhost","username","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 'Table1' 
$sql = "SELECT * FROM Table1"; 

// 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); 
?> 

現在,雖然我確實理解這裏到底發生了什麼,但它只從一張表中提取數據。如果我想從數據庫中的多個表中獲取數據,我如何編輯上面的代碼?

回答

0

這取決於你想如何實現在一個MySQL查詢,您可以連接的表,如:

SELECT o.*, c.companyName FROM orders o INNER JOIN customers c on o.customerId = c.id 

這將返回所有的訂單信息和客戶的公司名稱從相關表。

如果您想要返回多個不同的表格,您可能需要創建多個端點。例如可能是一個customers.php,orders.php。

就我個人而言,當爲移動項目創建後端時,我通常會使用Symfony2創建一個RESTful API,但這需要一些時間來學習。

這個tutorial可能有助於理解MySQL

+0

我有多個表。雖然有一個主表與其他表中的外鍵有關係。在這種情況下,它將是上面代碼中的'Table1'。所有的關係都是一對多的關係。 – luke

+0

上面的代碼和提供的鏈接將允許您創建需要獲取數據的連接,您可能需要多個不同的腳本才能獲得不同的結果 – Scriptable