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);
?>
Related
I learning android and trying to write some code to verify a username and password using a PHP script and a WAMP server. I keep getting undefined index errors from my PHP script. As far as I can ascertain that means my PHP script can't access the data from the URL. Here is the relevant code. Any help is appreciated.
//build url data to be sent to server
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
String result = "";
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/PasswordCheck.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("Connection", "Error in http connection "+e.toString());
}
Here is my PHP script
<?php
mysql_connect("localhost", "root", "") or die("could not connect to mysql");
mysql_select_db("drop-in") or die("database not found");
$username = $_POST["username"];
$suppliedPassword = $_POST["password"];
$databasePassword = "";
$output = "false";
$query = mysql_query("SELECT Password FROM users WHERE Username = '$username'") or die("query failed");
if(mysql_num_rows($query) > 0){
$row = mysql_fetch_assoc($query);
$databasePassword = $row['password'];
if($databasePassword == $suppliedPassword)
{
$output = "true";
}
}
print($output);
mysql_close();
?>
And here a picture of the server's reply
http://imgur.com/sQStI2D
EDIT: So I figured out that even though the PHP script is giving these errors the $username and $password variables contain the values my android app was attempting to pass along. However the presence of these errors is still messing with my code because the HTML for the error tables gets sent back to the android app in the response
To me it looks like your Android code isn't POSTing the "username" and "password" fields, that explains why the PHP script can't find them.
In your code, new ArrayList<NameValuePair>();, the length of the arrayList may be missing, by looking at this code sample: it looks like it should be new ArrayList<NameValuePair>(2);, you should try with that and see if resolves the issue.
Turns out it was a simple spelling error. I used a lower case 'p' in the word 'password' in my loop instead of an uppercase. Odd that it caused the error that it did.
You can try json_decode() function in PHP:
try to create A file on your server and put content of android request into simple text file you will get array output. in that file.
on your server in .php file write below code:
<?php
$data=file_put_content(collect.txt, $_POST);
// if you got to know object or array name from txt file use it.
$array=json_decode($data, true) // for array output.
print_r($array);
?>
and if you don't want to read from file you can directly use if you know array name, in json object
<?php
$array=json_decode($data) // remove true for use as an object output.
print_r($array);
?>
once you got your array assign values to new variables and do whatever you want with them. Update database or anything as per your requiremnet
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.
I'm connecting to local web server from android client and getting results back from mongodb database.
<?php
$Earth_radius = 6378.137; //KM
$required_distance = 20; //KM
if(! isset($_POST['long']) || ! isset($_POST['lat']) )
{
echo 'NOT SET'; //exit();
}
$long = $_POST['lat'];
$lat = $_POST['long'];
// open connection to MongoDB server
$conn = new Mongo('localhost');
// access database
$db = $conn->matabatdb;
// access collection
$collection = $db->matabat;
$center=array($long,$lat);
$radius=$required_distance/$Earth_radius; //convert to radians
echo 'Im Ok here ';
$result = $collection->find(array("loc"=>array('$within'=>array('$centerSphere'=>array($center,$radius)))));
echo ' I can reach here';
var_dump($result->getNext());
echo 'I do not reach this line';
?>
Any manipulation to $result doesn't provide any feedback response to android client
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseText = EntityUtils.toString(entity);
Pattern pattern=Pattern.compile(".*?<body.*?>(.*?)</body>.*?",Pattern.DOTALL);
Matcher matcher=pattern.matcher(responseText);
if(matcher.find()) {
String userID = matcher.group(1).trim();
}
else
Log.i(TAG," POST RESPONSE "+ responseText);
}
else
Log.i(TAG," POST RESPONSE is NULL");
The strange thing is If I made an html file and posted data manually the code works in the browser but regarding to android, I do not receive any data back or more specifically any data after manipulating the cursor. any echo statements before that line is received in Android.
Any help ?
If the PHP script works from the browser. Then it's perhaps a data encoding problem.
Try using json_encode($result->getNext()) instead of var_dump($result->getNext()).
I have an android app that sends a json string to my server and it is formatted as follows:
{"drink_name":"testing","phone_number":"5555555555"}
When I use the command: SELECT * FROM orders, it shows that blank entries were inserted into the table.
I think my issue is arising from my PHP script (mainly because I am new to PHP).
Am I parsing the json correctly?
Below is the script that I wrote.
<?php
$handle = mysql_connect('localhost',USERNAME,PASSWORD);
if($handle==false)
{
die('No database connection');
}
$db=mysql_select_db('r2bar2');
$json = file_get_contents('php://input');
$obj = json_decode($json);
mysql_query("INSERT INTO orders (phone_number, drink_name)
VALUES ('".$obj->{'phone_number'}."', '".$obj->{'drink_name'}."')");
mysql_close($handle);
?>
EDIT:
Here is my Android code if it is any help.
protected void sendJson(final String phnNmbr, final String drink) {
Thread t = new Thread(){
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost("http://kubie.dyndns-home.com/R2Bar2/sendOrder.php");
json.put("phone_number", phnNmbr);
json.put("drink_name", drink);
StringEntity se = new StringEntity( "orders: " + json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show();
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
}
catch(Exception e){
e.printStackTrace();
//createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
I had used the same method except for how you are trying to access json data on the server.
I had used $_POST array to access it and it worked well for me. Try using,
$json = $_POST['orders'];
$obj = json_decode($json);
This had worked perfectly well for me. All the best :)
(I dont think there is a problem with $handle since something is being inserted into the table)
I figured out what I was doing wrong. It seems as though I was passing in a raw data type. In order to parse the string, I used the following:
$obj = json_decode(file_get_contents("php://input"));
mysql_query("INSERT INTO orders (phone_number, drink_name)
VALUES ('".$obj->{'phone_number'}."', '".$obj->{'drink_name'}."')");
Thanks everyone for your suggestions.
You have make a connection to the DB as follws,you have missed the $handle to make connection
$handle = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$handle) {
die('Not connected : ' . mysql_error());
}
// make r2bar2 the current db
$db=mysql_select_db('r2bar2',$handle);
if (!$db) {
die ('Can\'t use r2bar2 : ' . mysql_error());
}
I could really need some help to my project.
I have an android app, that scans for wireless networks. I want to upload this data to a mysql database.
Android have database class:
public class Database {
public static void putServerData(String building, String floor, String room, String address, String signal){
String db_url = "http://**(IP ADDRESS)**/setdata.php";
#SuppressWarnings("unused")
InputStream is = null;
ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
request.add(new BasicNameValuePair("building",building));
request.add(new BasicNameValuePair("floor",floor));
request.add(new BasicNameValuePair("room",room));
request.add(new BasicNameValuePair("address",address));
request.add(new BasicNameValuePair("signal",signal));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(db_url);
httppost.setEntity(new UrlEncodedFormEntity(request));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
}
}
This is called by:
try {
Database.putServerData(building,floor, room, array1.get(1).toString(), array2.get(2).toString());
} catch (Exception e) {
Log.e("test", "test");
}
The server is a Win7 machine, with apache php and mysql
The setdata.php file:
<?php
$con = mysql_connect("localhost","root","pass");
if(!$con)
{
echo 'Not connected';
echo ' - ';
}else
{
echo 'Connection Established';
echo ' - ';
}
$db = mysql_select_db("android");
if(!$db)
{
echo 'No database selected';
}else
{
echo 'Database selected';
}
$building = $_POST['building'];
$floor = $_POST['floor'];
$room = $_POST['room'];
$ap_mac1 = $_POST['ap_mac1'];
$ap_strength1 = $_POST['ap_strength1'];
$ap_mac2 = $_POST['ap_mac2'];
$ap_strength2 = $_POST['ap_strength2'];
$ap_mac3 = $_POST['ap_mac3'];
$ap_strength3 = $_POST['ap_strength3'];
$ap_mac4 = $_POST['ap_mac4'];
$ap_strength4 = $_POST['ap_strength4'];
$ap_mac5 = $_POST['ap_mac5'];
$ap_strength5 = $_POST['ap_strength5'];
echo ($_POST['building']);
mysql_query("INSERT INTO wifiscan VALUES($nextid, '$building','$floor','$room','$ap_mac1','$ap_strength1','$ap_mac2','$ap_strength2', '$ap_mac3', '$ap_strength3', '$ap_mac4', '$ap_strength4', '$ap_mac5', '$ap_strength5')");
mysql_close(); ?>
This is not working. Im not sure i select the database in the correct way, could that be the problem?
Maybe this isnt so clear and ill will explain it further if you want.
Use some Log and maybe sprintfs to figure out what is exactly going on.
I#d start with the PHP. Try to open the URL from your browser and put some outputs in the PHP to see if everything works fine here. Post your results and you will probably get further help.