how to read an external mysql database - iphone

I'm trying to find how to read data from my database in my iphone app. The database is in my server, what I tried is similar to how I do that in Android (I'm not sure if is the best way):
NSString *hostStr = #"http://www.myip/notices.php";
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"Mysql response:is %#",serverOutput);
What I get is "Mysql response: is Array", what is true:
<?php
mysql_connect("localhost","user","pass");
mysql_select_db("database");
$q = mysql_query("SELECT id, title FROM jos_content WHERE catid=12 AND state=1 AND DATE(publish_up) <= NOW() ORDER BY DATE(publish_up) DESC");
while($e=mysql_fetch_assoc($q))
$output[]=array("id" => $e['id'], "title" => utf8_encode($e['title']));
echo $e;
print($output);
mysql_close();
?>
how should I do it?
Thank you in advance

From your php print the data as JSON it will be much easier to deal with it
In your PHP use
Instead of
print($output);
use
echo json_encode($output);
Then in your iOS app you could use this framewrok
Additional resources
How to parse JSON in iOS App
iPhone/iOS JSON parsing tutorial
To use SBJSon you would do the following
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
id object = [serverOutput JSONValue];
NSMutableDictionary *dictionary = (NSMutableDictionary *)object;
Now dictionary will contain the dictionary of values and keys

Related

How to separate JSON response in iphone

I have an application in which I am having a json response like this.
{"success":"true","message":"You have logged in","pserial":"1"} and I am separating with ":".
And I am getting data like this pSerial:"1"} but I want only 1 value.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSString *approvalString = [[strResp componentsSeparatedByString:#":"] objectAtIndex:3];
NSLog(#"pSerial:%#",approvalString);
for Example :
SBJsonParser *jsonPar = [[SBJsonParser alloc] init];
NSError *error = nil;
NSArray *jsonObj = [jsonPar objectWithString:jsonString error:&error];
id jsonObj = [jsonPar objectWithString:jsonString error:&error];
if ([jsonObj isKindOfClass:[NSDictionary class]])
// treat as a dictionary, or reassign to a dictionary ivar
else if ([jsonObj isKindOfClass:[NSArray class]])
// treat as an array or reassign to an array ivar.
Then get the value :
NSMutableArrary *userMutArr = [NSMutableArray array];
for (NSDictionary *dict in jsonObj)
{
User *userObj = [[[User alloc] init] autorelease];
[userObj setFirstName:[dict objectForKey:#"firstName"]];
[userObj setLastName:[dict objectForKey:#"lastName"]];
[userObj setAge:[[dict objectForKey:#"age"] intValue]];
[userObj setAddress:[dict objectForKey:#"address"]];
[userObj setPhoneNumbers:[dict objectForKey:#"phoneNumber"]];
[userMutArr addObject:userObj];
}
Hope you will understand. and read some Documents. it will help you.
It looks like you are in need of JSON Parsing. Here, what you want is JSON Parsing, not separating data from the JSON Response. JSON is the format of the data in which data is formatted in Key-Value pairs. You can fetch the "Value" of any object using the "Key".
Your first two lines are correct.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
Now, you can parse JSON Response like this :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];
NSString *pSerial = [json objectForKey:#"pserial"];
This will give you the value of "pserial" from your response. Similarly, you can get the values for "success" and "message". You can check it using this line :
NSLog(#"pserial :: %#",pserial);
You need to parse the JSON Response String, you can use any JSON parser like:
https://github.com/stig/json-framework/
And in your code do:
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSDictionary *ResponseDictionary = [strResp JSONValue];
NSString * pSerial = (NSString*)[ResponseDictionary objectForKey:#"pserial"];
Dont separation by ":" just use JSONValue your response is like
// {"success":"true","message":"You have logged in","pserial":"1"}
// with SBJsonParser parse your object like this
NSDictionary *responseJson = [YOUR-OBJECT JSONValue];
Note: dont forget to add Json header file
Its better you use any OpenSource Json Parser
Here is a stack post Comparison of different Json Parser for iOS

Parse json in objective-c for my iphone app

i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data:
[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use NSJSONSerialization. If you have your JSON data in a string you can do:
NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
Edit To get a specific value:
NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:#"projName"];
I would recommend using JSONKit library for parsing.
Here's a tutorial on how to use it.
You will basically end up with a dictionary and use objectForKey with your key to retrive the values.
JSONKit
or
NSJSONSerialization(iOS 5.0 or later)
I have had success using SBJson for reading and writing json.
Take a look at the documentation here and get an idea of how to use it.
Essentially, for parsing, you just give the string to the SBJsonParser and it returns a dictionary with an objectForKey function. For example, your code might look something like:
NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:#"projId"];
Use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];
No need to use third party classes. Objective-c already includes handling JSON.
The class NSJSONSerialization expects an NSData object or reads from a URL. The following was tested with your JSON string:
NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:&error]
For more options with NSJSONSerialization see the documentation.

iPhone and MySQL

First I need to say that I am new to iPhone development, so please I need you to be specific!
I'm developing an application for School scientific project,the question is: How can I insert data into a mysql table from UITextFields on the iPhone?
On my application I have 3 UITextFields, so I need to insert those UITextFields values into the mysql table. It doesn't matter the way you know to do that, I'm in a hurry and I just wanna to put it to work.
1-I working with this PHP code
<?php
if (isset ($_GET["matricula"]))
$matricula = $_GET["matricula"];
else
$matricula = "ELO";
$sql="INSERT INTO chatitems (user, message, matricula) VALUES ('$_GET[user]','$_GET[messages]','$_GET[matricula]')";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
//$sql = "insert into $DB_Table (matricula) values('$matricula');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
And I insert this CODE on my application(Xcode 4.1)
2
- (IBAction)insert:(id)sender
{
// create string contains url address for php file, the file name is phpFile.php, it receives parameter :name
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/phpFile.php?name=%#",txtName.text];
//NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/phpFile.php?name=%#",txtMatricula.text];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", strResult);
NSString *cont11 = [NSString stringWithFormat:#"http://localhost:8888/UEUO/insertMT.php?name=%#",txtName.text];
NSString *cont21 = [NSString stringWithFormat:#"http://localhost:8888/UEUO/insertMT.php?matricula=%#",txtMatricula.text];
NSData *cont12 = [NSData dataWithContentsOfURL:[NSURL URLWithString:cont11]];
NSData *cont22 = [NSData dataWithContentsOfURL:[NSURL URLWithString:cont21]];
NSString *cont13 = [[[NSString alloc] initWithData:cont12 encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", cont13);
NSString *cont23 = [[[NSString alloc] initWithData:cont22 encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", cont23);
}
This code works fine for only one UItextField, I need three3.
Repenting: How can I insert the values of three UITextFields into a MySql table using PHP and C++?
Please anything is helpful, if you know how please help me or send me a tutorial or a piece of code!
Your PHP script is looking for 3 parameters passed from a single request.
Your iPhone code is sending 2 different requests with 1 parameter each.
Your iPhone code should be sending 1 request with 3 parameters set, as with this sort of request:
NSString *cont11 = [NSString stringWithFormat:#"http://localhost:8888/UEUO/insertMT.php?name=%#&matricula=%#&message=%#",txtName.text, txtMatricula.text, txtMessage.text];
[NSData dataWithContentsOfURL:[NSURL URLWithString:cont11]];
I should also point out that you haven't sanitized your inputs. That's really bad. Sanitize your inputs.

Xcode IPhone Parse Server Output

I am sending some data to the server that is coming back as a string, but i need to parse it at the carriage return (new line)
The variable the output is being stored in is
NSString *serverOutput = [[NSString alloc] initWithData: dataurl encoding:NSASCIIStringEncoding];
The output is:
1bac92c2-b83a-4c93-9e11-831115825fa9\nmike1\nmike2\nfoo#bar.ca\n2
Any suggestions or help?
Something like this:
NSString *serverOutput = #"1bac92c2-b83a-4c93-9e11-831115825fa9\nmike1\nmike2\nfoo#bar.ca\n2";
NSArray *myData = [serverOutput componentsSeparatedByString:#"\n"];

How can I parse a longer JSON file than a NSString?

I'm a bit stuck in a project.
I was writing some code to get a JSON file and store it in an NSString before parsing it into a NSArray.
But I get an error:
2010-10-27 20:59:44.813 GeraldKervyn[21752:207] -JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x7637890 {NSLocalizedDescription=Unrecognised leading character}"
I think the problem is related to the limited value that an NSString can take.
BTW this is the feed I'm using : http://www.geraldkervyn.com/api/get_recent_posts/
What would be the most convenient way to parse this into an NSArray ?
Thanks !
First, Add the SBJson code to your project, courtesy of Stig Brautaset. Then do this...
NSString *subject = #"http://www.geraldkervyn.com/api/get_recent_posts/";
NSString *encodedSubject =
[subject stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *test = [NSString stringWithContentsOfURL:[NSURL URLWithString:encodedSubject]];
SBJsonParser *parser = [[SBJsonParser new] autorelease];
NSDictionary *json = [parser objectWithString:test];
NSArray *values = [json objectForKey:#"posts"];