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
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to fetch data from mysql database and populate it on a listview.
I am getting the ip address of my system like this
String link_url = "192.168.19.6";
Now in my wamp server I have a file called
/product_api/getDataProduct.php";
I now I want this file to called in eclipse I am doing this
link_url = Referensi.link+"/product_api/getDataProduct.php";
Please is this the right way of connecting android to mysql and how I do know if the file I am calling on eclipse is connected to mysql database.
this is the getDataOriduct.php file
<?php
include("koneksi.php");
$q = mysql_query('select * from produk');
$v = '{"info" : [';
while($r=mysql_fetch_array($q))
{
$ob = array("<br>","<b>","</b>");
if(strlen($v)<12)
{
$v .= '{"id_produk" : "'.$r['id_produk'].'", "nama_produk" : "'.$r['nama_produk'].'", "harga" : "'.$r['harga'].'", "deskripsi" : "'.$r['deskripsi'].'", "stok" : "'.$r['stok'].'", "gambar" : "'.str_replace($ob,"",$r['gambar']).'"}';
}
else
{
$v .= ',{"id_produk" : "'.$r['id_produk'].'", "nama_produk" : "'.$r['nama_produk'].'", "harga" : "'.$r['harga'].'", "deskripsi" : "'.$r['deskripsi'].'", "stok" : "'.$r['stok'].'", "gambar" : "'.str_replace($ob,"",$r['gambar']).'"}';
}
}
$v .= ']}';
echo $v;
?>
this is the included file
<?php
$conn = mysql_connect("localhost","root","");
$db = mysql_select_db("android_tokobaju");
?>
this is where the error took place and this method is defined in oncreate method
JSONParser jParser = new JSONParser();
String nlink_url = link_url +"/product_api/getDataProduct.php";
JSONObject json = jParser.AmbilJson(nlink_url);
This is the stacktrace
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ecommysql.yonandroid/com.ecommysql.yonandroid.PhotoProduk}: java.lang.IllegalStateException: Target host must not be null, or set in parameters.
This is the AmbilJson function
public JSONObject AmbilJson(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
Please with the above is my database connected to mysql db. Thanks
You are in a very wrong direction my friend. There are lots of problem in the code which you shared. You have to know something before you start.
Why shouldn't I use mysql_* functions in PHP
After that
JSON with PHP
After that your code will look like this
include("koneksi.php");
$q = mysql_query('select * from produk'); // change it too
$v['info'] = [];
while($r=mysql_fetch_array($q))
{
$ob = array("<br>","<b>","</b>");
$temp['id_produk'] = $r['id_produk'];
$temp['nama_produk'] = $r['nama_produk'];
$temp['harga'] = $r['harga'];
$temp['deskripsi'] = $r['deskripsi'];
$temp['stok'] = $r['stok'];
$temp['gambar'] = str_replace($ob,"",$r['gambar']);
$v['info'][] = $temp;
}
echo json_encode($v);
?>
After that on android side you have to use
Simple parse JSON from URL on Android and display in listview
You can't connect android to MySql directly you have to use any server
side language which will fetch data from the mysql and feed to the
android. In your case PHP is server side scripting language which is
fetching data from mysql and returning JSON as a response. By Android
making an HTTP request to the server you can get that JSON from the
server and then inflate the list with that data.
you should add username , password ,hostname and database.
add that they try again.
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
$dbase ="your_database";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password,$dbase)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//execute the SQL query and return records
$result = mysql_query("SELECT id, model,year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'model'}."Year: ". //display the results
$row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>
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?
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);
?>
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:
i just want to read the single line text that is echoed from the php web server .
but the my code reads the echoedd text along with the web pages source code i just want to remove the source code and get only the text is there any way to get text separately
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://www.rock.bugs3.com/check.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(newBasicNameValuePair("username",
et.getText().toString().trim()));
$Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(newBasicNameValuePair("password",
pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
i am new to both android as well as php .this is my php code which i have used
<?php
$hostname_localhost ="mysql.serversfree.com";
$database_localhost ="u154090_donor";
$username_localhost ="u154090_donor";
$password_localhost ="abcd";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
}
else {
echo "User Found";
}
mysql_close($localhost);
?>`
You should choose a better transport protocol between your client and server.
HTML is meant to be rendered by a browser, and implies how the data is visually represented.
If you have programmed an endpoint in your PHP server that you call the get some data (only raw data without visual representation) your PHP script should output the data you need encoded in XML or JSON.
If you PHP definitively outputs HTML, you should use a XML parser in your android application to get the data you need inside the HTML.
The data sent back is controled by your php script check.php, not be the client. If there's too much data being sent back, the bug is in your php script or in your web server configuration.