php - 使用 PHP 将 iOS 客户端连接到 MySql 数据库的最佳方法是什么?

标签 php mysql

我有 MySql 数据,我想从 iOS 获取数据

    <?php
   // Database credentials
   $host = 'localhost'; 
   $db = 'json'; 
   $uid = 'json'; 
   $pwd = 'json1';


    // Connect to the database server   
    $link = mysql_connect($host, $uid, $pwd) or die("Could not connect");

   //select the json database
   mysql_select_db($db) or die("Could not select database");

   // Create an array to hold our results
   $arr = array();
   //Execute the query
   $rs = mysql_query("SELECT id,userid,firstname,lastname,email FROM users");

   // Add the rows to the array 
   while($obj = mysql_fetch_object($rs)) {
   $arr[] = $obj;
   }

   //return the json result. The string users is just a name for the container object. Can be set anything.
   echo '{"users":'.json_encode($arr).'}';

?>

将 iOS 连接到 MySql 数据库的最佳方式是什么?

请帮忙!!

最佳答案

是的,这很好,但只需添加

header('Content-Type: application/json');

到 php,以便响应是 json 而不是 html。

您可以添加一些验证或错误处理,例如

try
{
  //Your DB query part

      // Connect to the database server   
    $link = mysql_connect($host, $uid, $pwd) or die("Could not connect");

   //select the json database
   mysql_select_db($db) or die("Could not select database");

   // Create an array to hold our results
   $arr = array();
   //Execute the query
   $rs = mysql_query("SELECT id,userid,firstname,lastname,email FROM users");

   // Add the rows to the array 
   while($obj = mysql_fetch_object($rs)) {
   $arr[] = $obj;
   }

   //return the json result. The string users is just a name for the container object. Can be set anything.


    if(count($arr) >0)
    {
   echo '{"users":'.json_encode($arr).'}';
    }
}

catch(PDOException $e) {

        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

制作一个 NSURLConnection 类,与您托管此 .php 文件的服务器通信,如果您使用 JSON 解析器或内置的 NSJSONSerialization 类,可以为您解析响应。你在这里试图做的是创建 iOS 应用程序用来与你的数据库对话的 web 服务,特别是查询。如果您要扩大规模,您应该尝试实现 SLIM 或 FAT-FREE 等框架。

关于php - 使用 PHP 将 iOS 客户端连接到 MySql 数据库的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18591668/

相关文章:

php - 在 yii2 中使用缓存时呈现动态 csrf 隐藏输入

javascript - 单击 <a> 标签时加载 div 内的 PHP 文件

javascript - 单击项目名称时打开/关闭子菜单

mysql返回某一行中不为0的列名

php - 如何在显示文本时保持输入文本的格式?

php - oci_connect() 仅适用于命令行

javascript - 提交总是重定向到同一页面操作不起作用

php - 我无法使用准备好的语句将数据输入到我的表中

mysql - Processlist中有这么多Binlog_dump连接?

php - 输出时意外的 '' (T_ENCAPSED_AND_WHITESPACE)