简体   繁体   English

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

[英]what is the best way to connect an iOS client to a MySql database using PHP?

I have MySql data and i want to fetch data from iOS 我有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).'}';

?>

what is the best way to connect iOS to MySql database ? 将iOS连接到MySql数据库的最佳方法是什么?

please help !! 请帮忙 !!

Yes this is fine but just add 是的,这很好,但只需添加

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

to the php so that the response is a json and not a html. 到php,以便响应为json而不是html。

You could add some validations or error handling like, 您可以添加一些验证或错误处理,例如,

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() .'}}';
    }
}

Make a NSURLConnection class that talks to the server where you are hosting this .php file and If you use a JSON parser or the inbuilt NSJSONSerialization class that can parse the response for you. 创建一个NSURLConnection类,该类与托管此.php文件的服务器进行通信;如果您使用JSON解析器或内置的NSJSONSerialization类,可以为您解析响应。 What you are trying to do here is creating webservices that the iOS app uses to talk to your db, specifically querying. 您在这里要做的是创建iOS应用用来与您的数据库对话的Web服务,特别是查询。 You should try implementing frameworks like SLIM or FAT-FREE if you are going to scale up. 如果要扩大规模,则应尝试实现SLIM或FAT-FREE之类的框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM