简体   繁体   中英

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

    <?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 ?

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.

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. What you are trying to do here is creating webservices that the iOS app uses to talk to your db, specifically querying. You should try implementing frameworks like SLIM or FAT-FREE if you are going to scale up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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