I've used sqlite3 before in an iPhone application, but how can I query out to an external SQL database sitting on my website?
Apple uses SQLite in many (most?) of the native applications running on Mac OS-X desktops and servers and on iOS devices such as iPhones and iPods. SQLite is also used in iTunes, even on non-Apple hardware.
SQLite and Android are particularly compatible, because SQLite database implementation is built into the Android operating system. While MySQL is more commonly found on servers where it can be used by web applications, SQLite is more commonly used for mobile applications and for permanently storing data.
Your app does not perform the actual query. The proper way to do this is to set up an API for your website so that the site does the querying and returns the appropriate data to your app.
Your API is generally going to be comprised of a number of end points that return data formatted for your app. For example, you might create a PHP or Python page that queries your database for all of the posts for a given user and returns them in a JSON or XML encoded array. (The data format is totally up to you. There are frameworks for parsing both formats available for iOS.)
For example, let's say you have a PHP page on your server that returns the current day of the week. Your PHP would look something like this:
<?php
echo date("l");
?>
Let's imagine that you've saved this as http://example.com/dayoftheweek.php
I recommend using the ASIHTTPRequest framework for performing HTTP requests from within your app. That said, let's go ahead and set up a connection to your PHP page. Assuming you have ASIHTTPRequest all set up in your project, here's what a request might look like:
NSURL *url = [NSURL URLWithString:@"http://example.com/dayoftheweek.php"]
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
[request setDelegate:self];
Now, you need implement the ASIHTTPRequest Delegate methods, to parse the returned data. The method which handles a completed request is shown here:
- (void)requestFinished:(ASIHTTPRequest *)request{
//Here you would store the returned data and/or parse it
}
To implement an API, your PHP pages would be more complex. You would build a more complex request , passing in variables and such, and the PHP page would act like a regular web service, returning the data that you have requested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With