I am trying to retrieve specific values from phpmyadmin database.I want to retieve the row where to=$username from mytasksend table.
But when i echo the variable i don't get any output.
What am i supposed to do?
Here's my php file
<?php
mysql_connect ("localhost","root","");
mysql_select_db("taskmanager");
$username= (isset($_POST['to'])) ? $_POST['to'] : '';
$q=mysql_query("SELECT `tasksentid` FROM `mytasksend` where `to` = $username") or die(mysql_error());
$output=array();
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print (json_encode($output));
mysql_close();
?>
and here's my java file
try{
HttpClient httpclient3 = new DefaultHttpClient();
HttpPost httppost3 = new HttpPost("http://10.0.2.2:80/selection.php");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("to",id));
Log.w("aaaaaaa",""+nameValuePairs);
httppost3.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient3.execute(httppost3);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
}
Try wrapping the $username under single quotes in the query.
"SELECT `tasksentid` FROM `mytasksend` where `to` = '$username'"
I'm no android expert, but looking at your PHP, shouldn't you have quotes around $username? You should also really validate/clean any data coming via $_POST
Related
I am a beginner in android development. I want to connect a php file to the android app. My php code is
<?php
$con = mysqli_connect("localhost", "root", "", "invoice_db");
if(mysqli_connect_errno($con)) {
echo "Failed to connect";
}
$response["sucess"]=0;
$invoiceid = $_POST['invc'];
$response = array();
$sql = "SELECT sl_no from invoice_table where invoice_id='$invoiceid'";
$result = mysqli_query($con,$sql);
if(!empty($result)) {
$row = mysqli_fetch_array($result);
$data = $row[0];
$response["sucess"] = 1;
}
mysqli_close($con);
?>
Here 'invc' is get from httpRequest ,
JSONObject json = jsonParser.makeHttpRequest(url_check_user, "POST", params);
And my JSONParser page contains,
if (method == "POST") {
// request method is POST
// defaultHttpClient
System.out.println("Inside json parser POST condition");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
System.out.println("Inside json parser POST condition" + params);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("From httpentity", httpEntity.toString());
System.out.println("ppppppppppppphhhhhhhhhhhhhhhhhhhhppppppppppp");
is = httpEntity.getContent();
}
Now I want to check , whether the parameters were passed to the php page or not. So I want to console/log cat the $invoiceid. How can it possible in Eclipse Ide?
If you want to print a variable inside PHP code, you can do echo $variable. However please note that PHP code will be executed on a server and not on your android device. Moreover your PHP code is vulnerable to sql injection attacks
You can use JSON encoding method in your php file to get a proper JSON response like this.
$response = array (
'invoiceid' => $verify_code,
);
print json_encode($response);
which will return a JSON string to your app in a format like
{"invoiceid":"null"}
which you can decode and log it like this
InputStreamReader isw = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isw);
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = br.readLine()) != null){
buffer.append(line);
}
String finalresult = buffer.toString();
JSONObject myobject = new JSONObject(finalresult);
String flag= myobject.getString("invoiceid");
log.e("mylog",flag)
so that it will be visible in your logcat file.
I'm passing some values from an android app to a PHP script. I get an undefined index error in my PHP script but the variables have the correct values when I print them out from within the script. I want these errors gone but I can't figure out why they are there in the first place. Here is how they are passed to the PHP script.
Java Code
//build url data to be sent to server
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
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,"utf-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("Connection", "Error in http connection "+e.toString());
}
PHP Code:
<?php
mysql_connect("localhost", "root", "") or die("could not connect to mysql");
mysql_select_db("drop-in") or die("database not found");
if(isset($_POST["username"])){
$username = $_POST["username"];
}
if(isset($_POST["password"])){
$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();
?>
EDIT: added PHP script (they aren't in the same file, the code tags are misbehaving)
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.
i am trying to get a single field from mySql through php and use it in my android app.. how can i get a single field from php to android without using json? im trying to set a radiobutton's text into the field i get? here's my php code:
<?php
$con = mysql_connect("localhost","root","pass123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("voting", $con);
$result = mysql_query("SELECT Name FROM ssc_president WHERE Party = '123'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$pname = $row['Name'];
//echo "Name: ".$row['Name'];
mysql_close($con);
?>
You can use XML to get single name from server other than that You will have to hard code text of radio button in android.
To get dynamic data from server you need to call webservice which give data either in XML or JSON. Its depend on which you are using.
From PHP, simply echo the field you want. Make sure that is all you print.
<?php
...
echo $mydata;
?>
And from Android, read it with an HttpClient
String result = "";
InputStream is=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("MyURLGoesHERE");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
String line = "";
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
}catch(Exception ex){
Log.e("Error",ex.toString());
}
Log.d("DataFromPHP",result);
My HttpPost code posts to my Database. But it posts blank values into it. I am new to this whole part of Android, so I am sure its a really dumb mistake but hopefully someone can help me out.
Android Code:
String name = "test";
String _score = String.valueOf(score);
String _time = String.valueOf(seconds);
try {
final HttpClient client = new DefaultHttpClient();
final HttpPost post = new HttpPost(
"http://www.laytproducts.com/plantzsubmithighscore.php");
final List pair = new ArrayList(3);
pair.add(new BasicNameValuePair("name", name));
pair.add(new BasicNameValuePair("score", _score));
pair.add(new BasicNameValuePair("time", _time));
post.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
String result = sb.toString();
Log.i("Plantz","FillBucket Highscore result:\n"+result);
} catch (Exception e) {
Log.e("Plantz", "Error in http connection: "+e.toString());
}
Php:
<?php
$con = mysql_connect("localhost","MY_USER","MY_PASS");
$name = $_GET["name"];
$score = $_GET["score"];
$time = $_GET["time"];
if(!$con){
echo("COULDN'T CONNECT! " . mysql_error());
die("COULDN'T CONNECT! " . mysql_error());
}
mysql_select_db("laytprod_plantz",$con);
mysql_query("INSERT INTO bucket_highscore (Name, Score, Time) VALUES ('$name','$score','$time')");
mysql_close();
?>
In your Android code, you're sending the query as part of the message body via HTTP POST. In the PHP code, you're attempting to read the values from $_GET. PHP code should be using $_POST, or better yet, $_REQUEST, in order to read values obtained through HTTP POST.
I am trying to POST data from my android to my sql server
This is in my android application
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("firstName",value));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
This is my php
$firstName = $_POST["firstName"];
$sql = "SELECT firstName FROM `colleague` WHERE `lastName`
LIKE '%$firstName%' LIMIT 0, 5 ";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) $output[] = $row['firstName'];
echo implode("<br/>",$output);
print(json_encode($output));
But this now selects the first five rows .. it does not receive anything in $firstName = $_POST["firstName"]; ??
php Notice
Undefined index: firstName in C:\xampp\htdocs\
http declaration
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.1/Search.php");
$firstName = $_POST['firstName']; try single quotations. do you have spaces in the value for $firstName? if it is encoded, do decoding in php. Example if you have Your(space)Name then encoded form will be Your+Name, if you dont decode it the query has encoded value for $firstName. Use urldecode($_POST['firstName']) to decode the encoded url content