我在 PHP/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);
?>
现在,虽然我在一定程度上理解这里发生的事情,但它只从一个表中获取数据。如果我想从数据库中的多个表中获取数据,我该如何编辑上面的代码?
最佳答案
这取决于您要实现的目标,您可以在 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
关于php - 使用 phpMyAdmin for xcode 从 MySQL 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37214647/