I get a lot of clients asking me about making mobile apps that connect to their websites to retrieve data, allow users to login, etc. Most of them have PHP-based sites, but don't have any clue about making APIs to interface with them. They ask me why I can't just connect directly to their SQL databases. I don't think that's a good thing to do from a mobile app. I would prefer they have some sort of API in place.
As far as PHP-based sites go, what are the best options when it comes to implementing an API for this purpose?
You want to look into RESTful web services. Have a look at the wiki for this here. Your client's need to essentially build PHP applications that serve the underlying data of their websites through some REST-compliant data type e.g. JSON, XML, SOAP, etc. There are a number of in-built PHP functions that enable the quick conversion of PHP data structures into these formats. This would enable you to build mobile apps that make HTTP requests to get data which it can then display in it's own unique way.
An example for a JSON powered service could be as follows:
$action = $_GET['action'];
switch($action) {
case 'get-newest-products':
echo json_encode(getNewestProducts());
break;
case 'get-best-products':
echo json_encode(getBestProducts());
break;
.
.
.
default:
echo json_encode(array());
break;
}
function getNewestProducts($limit = 10) {
$rs = mysql_query("SELECT * FROM products ORDER BY created DESC LIMIT $limit");
$products = array();
if (mysql_num_rows($rs) > 0) {
while ($obj = mysql_fetch_object($rs)) {
$products[] $obj;
}
}
return $products;
}
function getBestProducts($limit = 10) {
$rs = mysql_query("SELECT * FROM products ORDER BY likes DESC LIMIT $limit");
$products = array();
if (mysql_num_rows($rs) > 0) {
while ($obj = mysql_fetch_object($rs)) {
$products[] $obj;
}
}
return $products;
}
You could query the API as follows (with mod_rewrite on) http://myapi.mywebsite.com/get-newest-products