iPhone and MySQL - iphone

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.

Related

iOS API in Parse - One to Many relation

I am using parse for the backend part of my iPhone App.
We can have a one to many relation in Parse which described in Relational Data.
This code works fine to retrive the data:
PFQuery *query = [PFQuery queryWithClassName:#"Comment"];
PFObject *fetchedComment = [query getObjectWithId:#"0PprArjYi3"];
NSString *content = [fetchedComment objectForKey:#"content"];
printf("%s", [content UTF8String]);
But when I use their codes provided in the Link, it returns null:
PFObject *post = [fetchedComment objectForKey:#"parent"];
[post fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
title = [post objectForKey:#"title"];
}];
printf("%s", [title UTF8String]); // RETURN NULL
Can anybody tell me what is wrong in this code? The problem could be fetchedcomment.
Addenda
This one also got an exception:
PFQuery *query = [PFQuery queryWithClassName:#"Comment"];
PFObject *fetchedComment = [query getObjectWithId:#"0PprArjYi3"];
PFObject *post = [fetchedComment objectForKey:#"parent"];
NSString *title = [post objectForKey:#"title"];
printf("%s", [title UTF8String]);
The method fetchIfNeededInBackgroundWithBlock is, as the name suggests, performed in background. Your code asks for a fetch and then immediately continues to the printf. At that point in time, the data hasn't been fetched yet, so title is probably still nil.
You have two options -
Use a synchronous method, such as [post fetch]: instead of [parent fetchInBackground...].
[post fetch];
title1 = [post objectForKey:#"title"];
Print the title inside the block that gets executed when the fetchInBackground... method finishes.

how to read an external mysql database

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

From PHP to iPhone table

I have a file named numbers.php on my ftp with the following content:
1/Brian/Red
2/Simon/Blue
3/Louise/Red
How do I get that into a table?
I need the table to show:
Brian
Simon
Loiuse
in the cells and then when you click on one of the names it takes you to a page with the colour matching the name.
I use this code when I just need to read a single line in a php file and output to textfields:
NSString *queryString = [NSString stringWithFormat: #"http://website.com/numbers.php"];
NSData *dataRequest = [NSData dataWithContentsOfURL: [ NSURL URLWithString: queryString]];
NSString *serverOutput = [[[NSString alloc] initWithData:dataRequest encoding: NSASCIIStringEncoding] autorelease];
urlTextField.text = serverOutput;
NSArray *splitString = [serverOutput componentsSeparatedByString: #"/"];
NSString *idOut = [splitString objectAtIndex: 0]; NSString *nameOut = [splitString objectAtIndex: 1]; NSString *colorOut = [splitString objectAtIndex: 2];
idTextField.text = idOut; nameTextField.text = nameOut; colorTextField.text = colorOut;
But I am a bit in doubt when it comes to multiple lines and how to get them into my table view. I assume I need to put the lines into an array?
First, I generate plist-Data on the server with the free avaliable CFPropertyList. Why, because it is verry easy to import plist-structures later.
In the app you can import data this way:
NSArray * myArray = [NSArray arrayWithContentsOfURL:[NSURL
URLWithString:#"http://url.com/foo.plist"]];
you can use NSMutableArray instead when you modifing myArray.
cheers

iphone: nsdata encoding after retrieval - why so strange?

I have a strange problem with my current app development. the aim of my app is to receive several xhtml websites via NSURLSConnection (yes, no ASIHTTPRequest framework), save them in an array and post them via NSURLConnection to a webservice, which parses some information for me.
problem: I have really strange encoding problems and tried a lot of workarounds.
receiving of xhtml website:
(void)connection:(CustomURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef) [response textEncodingName]);
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
[lastSearch.dataObjectsEncoding setObject:[response textEncodingName] forKey:connection.tag ];
[receivedData setLength:0];}
afterwards I work with the data and want to send it over to the webservice. therefor I do some preparations:
method 1:
NSMutableString *data = [[NSMutableString alloc] initWithData:theData encoding:NSASCIIStringEncoding];
NSArray *escapeChars = [NSArray arrayWithObjects: #"€", #"\n", #";" , #"/" , #"?" , #":" ,
#"#" , #"&" , #"=" , #"+" ,
#"$" , #"," , #"[" , #"]",
#"#", #"!", #"'", #"(",
#")", #"*", nil];
NSArray *replaceChars = [NSArray arrayWithObjects: #"%E2%82%AC", #"", #"%3B" , #"%2F" , #"%3F" ,
#"%3A" , #"%40" , #"%26" ,
#"%3D" , #"%2B" , #"%24" ,
#"%2C" , #"%5B" , #"%5D",
#"%23", #"%21", #"%27",
#"%28", #"%29", #"%2A", nil];
int len = [escapeChars count];
int i;
for(i = 0; i < len; i++)
{
[data replaceOccurrencesOfString: [escapeChars objectAtIndex:i]
withString:[replaceChars objectAtIndex:i]
options:NSLiteralSearch
range:NSMakeRange(0, [data length])];
}
method 2:
NSMutableString *data = [[NSMutableString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
method 3:
CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef) [lastSearchParam.dataObjectsEncoding objectForKey:key]);
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
NSMutableString *data = [[NSMutableString alloc] initWithData:theData encoding: encoding];
method 4:
NSString *data = [[NSString alloc] initWithBytes:theData length:[theData length] encoding:NSUTF8StringEncoding];
method 5:
NSString *data2 = [data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
after I added some stuff I want to HTTP POST the received XHTML to the webservice. to encode the whole parameters and the received data I add everything to a big string an do a
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
most websites are in UTF-8. so I first tried "method 2". if I NSLog the whole received data, everything seems fine, I can view the correct HTML source code, even the € sign is displayed correctly. but if I transmit the HTTP POST to the webservice, there is not all XHTML received by the web service. some special chars seems to break the transmission, e.g. a ";" sign.
so I searched the internet and came up with "method 1", parsing the received xhtml websites to ASCII and do some selfmade special char conversation - this worked for most signs, but e.g. the "€" didn't work and wasn't correctly received by the web service. but in this case, everything got over to the webservice - but sadly with wrong chars.
next try was "method 3", I saved the encoding of the websites while receiving them and use that information later on. but here was the same problem as with UTF8 encoding: the transmission was breaking by some special chars...
"method 4" and "method 5" didn't work as well..
question: why does the transmission breaks during my HTTP POST to the web service?

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"];