使用PHP将iOS客户端连接到MySql数据库的最佳方式是什么?
我有MySql数据,我想从iOS获取数据使用PHP将iOS客户端连接到MySql数据库的最佳方式是什么?,php,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 co
<?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');
以使响应是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应用程序用来与您的db对话的Web服务,特别是查询。如果要扩大规模,您应该尝试实现SLIM或FAT-FREE之类的框架。是的,这很好,但只需添加
header('Content-Type: application/json');
以使响应是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应用程序用来与您的db对话的Web服务,特别是查询。如果要扩大规模,您应该尝试实现SLIM或FAT-FREE之类的框架