ios json not working when using include() - php

I have an app that receives a JSON file generated by my jason.php script and displays the data in a table view.
It works fine until I try to use 'include(db_connect.php)' in my jason.php file to pass the database log in details to it.
Running my php script, with 'include(db_connect.php)', does work in a browser (returns the JSON file formatted correctly) but it doesn’t work on my phone.
However..
It does work on my phone if I just paste the contents of db_connect.php into the jason.php file...and it returns exactly the same JSON file in a browser.
Both ways return exactly the same JSON text in browser.
All the app does is expect to receive a JSON file from a specified URL, it does’t pass anything to it. Just visits the URL and stores whats returned in an NSData object.
If anyone knows why this is happening I would be grateful to know!
Thanks
jason.php: this returns a the JSON script perfectly in my browser
<?php
require("db_connect.php");
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM cities";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
db_connect.php the log in details
<?php
$host = "xxxxx"; //Your database host server
$db = "xxxxx"; //Your database name
$user = "xxxxx"; //Your database user
$pass = "xxxxx"; //Your password
$connection = mysql_connect($host, $user, $pass);
?>
jason_pasted.php this is exactly the same as jason.php but the contents of db_connect.php are just pasted in - produces exactly the same result in browser, and also works when used in my app.
<?php
$host = "xxxxx"; //Your database host server
$db = "xxxxxx"; //Your database name
$user = "xxxxx"; //Your database user
$pass = "xxxxxx"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM cities";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
ViewController.m extract from the app code
-(void) retrieveData
{
NSURL *url = [NSURL URLWithString:jsonURL];
NSData *data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//set up cities array
citiesArray = [[NSMutableArray alloc]init];
for (int i=0;i<[json count]; i++)
{
//create city object
NSString *cID = [[json objectAtIndex:i] objectForKey:#"id"];
NSString *cName = [[json objectAtIndex:i] objectForKey:#"cityName"];
NSString *cState = [[json objectAtIndex:i] objectForKey:#"cityState"];
NSString *cPopulation = [[json objectAtIndex:i] objectForKey:#"cityPopulation"];
NSString *cCountry = [[json objectAtIndex:i] objectForKey:#"country"];
City *myCity = [[City alloc] initWithCityID:cID
andCityName:cName
andCityState:cState
andCityPopulation:cPopulation
andCityCountry:cCountry];
//add city oject to city array
[citiesArray addObject:myCity];
}
[davesTableView reloadData];
}
TL;DR the app works perfectly with jason_pasted.php but not jason.php.
jason.php and jason_pasted.php return exactly the same JSON script when opened in a browser.
String returned from jason.php and jason_pasted.php
(
{
cityName = London;
cityPopulation = 8173194;
cityState = London;
country = "United Kingdom";
id = 1;
},
{
cityName = Bombay;
cityPopulation = 12478447;
cityState = Maharashtra;
country = India;
id = 2;
},
{
cityName = "Kuala Lumpur";
cityPopulation = 1627172;
cityState = "Federal Territory";
country = Malaysia;
id = 3;
},
{
cityName = "New York";
cityPopulation = 8336697;
cityState = "New York";
country = "United States";
id = 4;
},
{
cityName = Berlin;
cityPopulation = 3538652;
cityState = Berlin;
country = Deutschland;
id = 5;
}
)
error returned only when NSUrl points to jason.php
2014-02-13 11:43:34.760 JSONios[4655:60b] JSON error: Error Domain=NSCocoaErrorDomain Code=3840
"The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or
object and option to allow fragments not set.)
UserInfo=0x14659c40 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

This is placed in an answer for formatting:
Do not ignore errors!
Incorrect:
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
Note: The docs do not specify that nil may be passed for the error parameter.
Correct:
// There is an assumption that the JSON head is a dictionary.
NSError *error;
NSDictionary *jsonAsDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (jsonAsDict == nil) {
NSLog(#"JSON error: %#", error);
}
else { // For debug only
NSLog(#"JSON: %#", jsonAsDict);
}
Now, what happens with this code?
Also please provide the JSON string if possible.
Oh, I personally to not care how the php creates the JSON, all I need to see is the JSON.
Still having trouble: NSLog the data as a string:
NSLog(#"data: %#", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
If no data add the error parameter to
dataWithContentsOfURL:options:error:
in place of dataWithContentsOfURL:

Related

Swift http delete request with php not working

I had tried many times in Swift, seem the problem happened in the PHP file. i dont know the data tpye of $revaID correct i get $revaID value from swift, i want to use revaID to delete row from table reservation ,it is auto created.please help
<?php
$host = "127.0.0.1";
$username = "root";
$password = "password";
$dbname = "project";
// Connect to server
$connect=mysqli_connect("127.0.0.1", "root", "password","project")
or die ("Sorry, unable to connect database server");
$revaID = $_POST["revaID"]; ;
$UserID = $_["UserID"];
// Run the query
$query = "DELETE FROM reservation WHERE revaID = '$revaID'";
$result = mysqli_query($connect,$query);
////////////////////ignore///////// //////////////////
if ($result) {
print $result;
print "Suss";
print $revaID;
} else {
print "Failed to delete record!";
print(mysqli_error($connect));}
////////////////// ////////////////// //////////////////
////////////////////ignore////////////////////////
if ($revaID){
set_include_path('/Library/WebServer/Documents/');
$id2 = array();
$id2['revaID'] = $revaID;
// Loop through each row in the result set
$json = json_encode($id2, JSON_NUMERIC_CHECK );
file_put_contents('deleterevaID.php',$json,FILE_USE_INCLUDE_PATH);}
////////////////// //////////////////
mysqli_close($connect);
?>
and this is my swife code, when editingStyle == .delete , i got $revaID.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
let UserID = userinfo[indexPath.row]
// print(UserID)
userinfo.remove(at:indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
// Service.shared.deletePost(revaID:UserID.revaID) { (err) in
// }
let urlStr = "http://localhost/deleteres.php"
if let url = URL(string: urlStr) {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "DELETE"
let body = "revaID=\(UserID.revaID)"
print("ID:",UserID.revaID)
if let data = body.data(using: .utf8) {
let dataTask = URLSession.shared.uploadTask(with: urlRequest,
from: data, completionHandler: {
data, response, error in
if let error = error{
print("error: \(error.localizedDescription)")
}
// print(UserID.revaID)
//self.refreshBtnClicked(self)
})
dataTask.resume()
}
}
}
}
in a swift file, you are sending data with get method and in a PHP file you are trying to get data with post method.
so instead of this :
$revaID = $_POST["revaID"]; ;
try to get data by get method
$revaID = $_GET["revaID"]; ;

Send UTF8 String from UITextField over HTTP link

I'm using php method as web service to add user_comment to mysql database.
<?php
require '../database/connection.php';
extract($_POST);
if (isset($_GET['book_ID'])) {
$book_ID = $_GET['book_ID'];
$user_ID = $_GET['user_ID'];
$theComment = $_GET['theComment'];
}
if (!$db) {
$json[] = array("Message" => "Connection failed");
echo json_encode($json);
}
$sql = mysql_query("INSERT INTO Comment (user_ID , book_ID , theComment) VALUES ('$user_ID','$book_ID','$theComment')");
mysql_query($sql, $db);
$json[] = array("Message" => "Done");
echo json_encode($json);
everything fine if I type English but I have problem with Arabic
Objective-C:
-(NSString *)addCommentForBook:(NSString *)bookID userID:(NSString *)userID theComment:(NSString *)theComment{
NSString *dt = [NSString stringWithFormat:#"?book_ID=%#&user_ID=%#&theComment=%#",bookID,userID,theComment];
NSURL *myURL = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"http://www.myweb.com/library/Books/addCommentForBook.php%#",dt]];
NSMutableDictionary *theArray;
NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
if (myData) {
id myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];
theArray = (NSMutableDictionary *)myJSON;
}
return [[theArray valueForKey:#"Message"]objectAtIndex:0];
}
If I test from Browser work php work fine with Arabic but from iOS not work
Any one tell me what's wrong or do I need to convert the string from UITextField first or?

problems getting data from localhost:8888 in objective c using json

I am trying to use a server for the first time.
I have downloaded MAMP and have a local sever on my mac http://localhost:8888
I have a php file jsontest.php that shows my data from a SQL database
<?php
// Database credentials
$host = 'localhost';
$db = 'json';
$uid = 'json';
$pwd = 'json1';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
// Create an array to hold our results
$arr = array();
//Execute the query
$rs = mysql_query("SELECT id,userid,firstname,lastname,email FROM users");
// Add the rows to the array
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
?>
When i go to to http://localhost:8888/jsontest.php (the jsontest.php file is stored in MAMP/htdocs) I can see my data:
{"users":[{"id":"1","userid":"fhardy","firstname":"Frank","lastname":"Hardy","email":"fhardy#hauntedclock.com"},{"id":"2","userid":"jhardy","firstname":"Joe","lastname":"Hardy","email":"jhardy#hauntedclock.com"},{"id":"3","userid":"ndrew","firstname":"Nancy","lastname":"Drew","email":"ndrew#hauntedclock.com"},{"id":"4","userid":"sdoo","firstname":"Scooby","lastname":"Doo","email":"sdoo#mysterymachine.com"}]}
I then use the following objective c code to read from this server:
NSURL *url = [NSURL URLWithString:#"http://localhost:8888/jsontest.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; //
NSLog(#"jsonArray: %#", jsonArray);
But the app crashes with the error
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
I know the error is coming from my server as it works with the server from a tutorial. But i cannot get it to work with my local server on my mac. I have tried using just http://localhost/jsontest.php but it still doesn't work.
Any help would be greatly appreciated.
Instead of localhost, put your IP.
That's it...
This is how you will get your local IP.
Also check this

IOS to PHP, How to store TimeStamp from IOS and store into MYSQL via PHP

I have a table that needs to store the time stamp. The time stamp is created client side the sent to PHP script and i need to know how i store this time stamp into MYSQL table.
Also what data type do i need to set in MYSQL, the field data type that needs to store this time stamp?
IOS code:
CGRect screenRect = [[UIScreen mainScreen] bounds];
UIActivityIndicatorView *activityIndicator;
activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.frame = CGRectMake(0.0, 0.0, screenRect.size.width, screenRect.size.height);
activityIndicator.backgroundColor = [UIColor colorWithRed:0.0f/255 green:0.0f/255 blue:0.0f/255 alpha:0.9f];
activityIndicator.center = self.view.center;
[self.view addSubview: activityIndicator];
[activityIndicator startAnimating];
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 3) Load picker in background
dispatch_async(concurrentQueue, ^{
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
NSString *myRequestString = [NSString stringWithFormat:#"ThreadName=%#&ThreadDesc=%#&CatId=%d&UID=%d&TimeStamp=%f", textFieldThreadName.text, textFieldThreadDesc.text, rowCategory, self.userID, timeStamp];
NSString *response = [self setupPhpCall:myRequestString :#"insertThread.php"];
dispatch_async(dispatch_get_main_queue(), ^{
[self insertedThread:response];
[activityIndicator stopAnimating];
});
});
PHP Code:
<?php
include "connect.php";
$threadName = $_POST["ThreadName"];
$threadDesc = $_POST["ThreadDesc"];
$catId = $_POST["CatId"];
$uid = $_POST["UID"];
$date = $_POST["TimeStamp"];
$qry = "INSERT INTO Thread(T_U_ID,T_C_ID,T_Name,T_Description,T_Flagged,T_Rated) VALUES('$uid','$catId','$threadName','$threadDesc',$date,0,0)";
$result = mysqli_query($conn, $qry);
if($result){
echo 'inserted';
exit();
}else{
echo 'not inserted';
exit();
}
mysqli_close($conn);
?>

How do I notify my iPhone app via php that a name has been added to a database or not?

My iPhone app communicates through a php file with my mySql database. Everything works fine. But when I send the form and the username already exists, the php file should somehow backfire a notification. What should I do ?
php File
$query = "SELECT username FROM userData WHERE username = '$username'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
// WHAT SHOULD BE DONE HERE TO NOTIFY iPHONE ?
}
I could think of a way, but it I think there is a better and more efficient way to do it.
[EDIT]
This is what I did to get the response:
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error];
NSDictionary *jsonDictionaryResponse =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"json response = %#", jsonDictionaryResponse);
[/EDIT]
He does not really need a push notification. Just need a response back from the server.
$query = "SELECT username FROM userData WHERE username = '$username'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
// WHAT SHOULD BE DONE HERE TO NOTIFY iPHONE ?
sendResponse(200, json_encode('SUCCESS Notification'));
}
Where sendResponse looks like this
// Helper method to send a HTTP response code/message
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . 'OK';
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}

Categories