views:

1776

answers:

2

Anyone have any suggestions on how to set up both the php and the cocoa side of calling php functions? As a quick idea of what I want to do, I want to be able to to populate two tables with data and add/remove data from the db. So I want to set up a few functions in php that I can call from my iPhone code that will return values from my queries. I should note that my db is MySQL.

Mostly I'm interested in the syntax so if you have any code examples that I can play around with that would be super helpful.

Thanks in advance!

+4  A: 

Well, to get some data over HTTP protocol in iPhone, you could use:

NSString *urlstr = [[NSString alloc] initWithFormat:@"http://www.yourserver.com/yourphp.php?param=%d", paramVal];
NSURL *url = [[NSURL alloc] initWithString:urlstr];
NSString *ans = [NSString stringWithContentsOfURL:url];
// here in ans you'll have what the PHP side returned. Do whatever you want
[urlstr release];
[url release];

Now, on the PHP, you can return the data the way you want. I.E., and XML which you will then parse on the iPhone side.

Pablo Santa Cruz
That definitely works. I guess what I need more clarification on is the paramVal you have in your example above. Is the paramVal the function you are trying to call?
Jeff
Just don't use XML unless you absolutely have too. Go for something simpler like csv.
John Fricker
No, paramVal is just an example of an integer value you are going to send to your PHP file.http://www.yourserver.com/yourphp.php?param=4747So, in yourphp.php you'll get:$p = $_GET["param"];// $p is going to be equal to 4747
Pablo Santa Cruz
Thanks! that totally worked. I was even able to convert to XML and parse that data back in.
Jeff
do you know how you could prevent someone from running the same script from a browser?
Jeff
You could check User-Agent header at PHP's side. If it's something different than iPhone's Safari user agent, you could stop serving the request. It's not infallible though. Anyone can tamper with HTTP headers. But it will be useful to stop average user.
Pablo Santa Cruz
You could also setup HTTP authentication via htaccess, and your iPhone app could pass the credentials in when making the request.
pixel
A: 

Hi, what happens if your PHP script needs to pull out lots of data out of a database and there is let's say 1-2 seconds delay? How can you 'wait' until the ans variable has a value?

RedCrystal