I'm creating a quiz app and i have to retrive all the question to display.this is my php and java code.i'll store the data in another array.i'm not able to fetch any data from my sql table.
StringRequest stringRequest = new StringRequest(Request.Method.POST,insertUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
for(int k=0;k<jsonArray.length();k++)
{
question[k]=jsonObject.getString("question");
opta[k]=jsonObject.getString("optionA");
optb[k]=jsonObject.getString("optionB");
optc[k]=jsonObject.getString("optionC");
optd[k]=jsonObject.getString("optionD");
ans[k]=jsonObject.getString("Answers");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Quiz.this,error.toString(),Toast.LENGTH_LONG ).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
params.put(ITEM_COURSE,data);
return super.getParams();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
This is my php code
<?php
require 'initquiz.php';
global $connect;
$response = array();
$course=$_POST["course"];
$query = "SELECT * FROM questions WHERE course='$course'";
$result= mysqli_query($connect,$query) or die(mysqli_error($connect));
$response= array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$question = $row[0];
$optionA = $row[2];
$optionB= $row[3];
$optionC = $row[4];
$optionD= $row[5];
$Answers= $row[6];
array_push($response,array("question"=>$question,"optionA"=>$optionA,"optionB"=>$optionB,"optionC"=>$optionC,"optionD"=>$optionD,"Answers"=>$Answers));
}
}
echo json_encode($response);
?>
Issues with your code:
You mixed mysql_* and mysqli_* extension
Your code is vulnerable to SQL injection, use prepared statements
Your fetch could be much simpler
Try to avoid SELECT *, instead select specific fields
Try this approach:
$response = [];
if(isset( $_POST["course"])){
$mysqli = new mysqli("host", "user", "password", "db");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM questions WHERE course = ?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("s", $_POST["course"]);
$stmt->execute();
while ($row = $stmt->fetch_assoc()) {
$response['data'][] = $row;
}
$response['success'] = true;
}
$mysqli->close();
}else{
$response['data'] = 'No Course Sent';
$response['success'] = false;
}
echo json_encode($response);
Related
Hello I'm send an JSON object from android using volley library. I can not receive this JSON object in PHP. I checked by echo ING my JSON data I can see the object in my 'OnResponse Method'. It would be my pleaser if anyone can help me to solve it. I'll owe you a great debt. Here is my code ->
Android Volley Code ->
private void registerUser() {
JSONObject postObject = new JSONObject();
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject historyObject = new JSONObject();
String url ="http://helpinghandbd.org/app/index.php";
try {
//historyObject.put("id","1");
historyObject.put("email","1234");
historyObject.put("password","1234");
postObject.put("user",historyObject);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("LoginActivityJsonObject",""+postObject);
JsonObjectRequest objRequest = new JsonObjectRequest(Request.Method.POST, url,postObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("LoginActivity","OnResponse: "+response);
Toast.makeText(LoginActivity.this, String.valueOf(response), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("OnError", String.valueOf(error.getMessage()));
}
});
queue.add(objRequest);
}
JSON Format is ->
{ 'user':{
'email':'1234',
'password':'1234'
}
}
And Finally PHP Code is ->
<?php
$data = file_get_contents("php://input");
//echo $data; -> //{ 'user':{'email':'1234','password':'1234'}};
$decode = json_decode($data,true);
$email = $decode->user['email'];
$password = $decode->user['passowrd'];
$servername = "localhost";
$username = "helpinghandbd_app";
$password = "Demopass000";
$dbname = "helpinghandbd_app";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$data = file_get_contents("php://input");
//{ 'user':{'email':'1234','password':'1234'}};
$sql = "INSERT INTO users (id,email,password)
VALUES (null, '$email', '$password')";
if ($conn->query($sql) === TRUE) {
echo $data;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I can not receive JSON Object in PHP. Thanks in advance.
In your php code, change
$decode = json_decode($data,true);
$email = $decode->user['email'];
$password = $decode->user['passowrd'];
to
$decode = json_decode($data,true);
$email = $decode['user']['email'];
$password = $decode['user']['passowrd'];
the query from the application is not being updated , but I can do it manually
this is the url , note if you exucte it , the query will be run
http://justedhak.com/old-files/singleactivity.php?id=1&likes=14
this is the php, i know php needs improvement
$id= intval($_GET['id']);
$likes= intval($_GET['likes']);
$con = mysqli_connect($host,$uname,$pwd,$db) or die(mysqli_error());
echo $id;
$sql1="UPDATE OBJECTS SET LIKES=$likes WHERE ID=$id";
$result = mysqli_query($con,$sql1);
this is the code
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute()
{
Log.e("GetText","called");
}
#Override
protected String doInBackground(String... params) {
String json = "";
try{
RequestBody formBody = new FormEncodingBuilder()
.add("id", "1")
.add("likes", "10")
.build();
Request request = new Request.Builder()
.url("http://justedhak.com/old-files/singleactivity.php")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//insert username, password and login true after successful login.
//redirect to main activity
} catch (IOException e){
Log.e("MYAPP", "unexpected JSON exception", e);
}
return "success";
}
I am not getting errors , and the asyctask looks good
Your API support only GET method. You don't need to create a RequestBody for that.
Try this,
#Override
protected String doInBackground(String... params) {
try {
String id = "1";
String likes = "14";
String url = "http://justedhak.com/old-files/singleactivity.php?id=" + id + "&likes=" + likes;
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}
Log.e("MYAPP", response.body().string());
} catch (IOException e){
Log.e("MYAPP", "unexpected JSON exception", e);
}
return "success";
}
Try this code in PHP,
<?php
$id = intval($_GET['id']);
$likes = intval($_GET['likes']);
// Create connection
$conn = new mysqli($host, $uname, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE OBJECTS SET LIKES=$likes WHERE ID=$id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
I am trying to insert a new record and same time it check the record is exist or not.but the query fails to show the function please give me suggestions. when application runs it shows FAILURE ( the Data could not be inserted. Signup failed.)this message from java file.I want to display messages in application records inserted or record exist.
//java file
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String fullName = arg0[0];
// String userName = arg0[1];
String passWord = arg0[1];
String phoneNumber = arg0[2];
String emailAddress = arg0[3];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?fullname=" + URLEncoder.encode(fullName, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
data += "&phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");
data += "&emailaddress=" + URLEncoder.encode(emailAddress, "UTF-8");
link = "http://mydoamin.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successfull.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted. Signup failed.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
//php file
<?php
$con=mysqli_connect("localhost","user","password","database");
if (mysqli_connect_errno($con))
{
echo '{"query_result":"ERROR"}';
}
$fullName = $_GET['fullname'];
//$userName = $_GET['username'];
$passWord = $_GET['password'];
$phoneNumber = $_GET['phonenumber'];
$emailAddress = $_GET['emailaddress'];
$sql = "INSERT INTO users10 (fullname,password,phone,email)
SELECT * FROM (SELECT '$fullName', '$passWord', '$phoneNumber','$emailAddress') AS tmp
WHERE NOT EXISTS (
SELECT name FROM users10 WHERE phone = '$phoneNumber' OR email='$emailAddress'
) LIMIT 1 ";
$result=mysqli_query($con,$sql);
if($result == true)
{
echo '{"query_result":"SUCCESS"}';
}else{
echo '{"query_result":"FAILURE"}';
}
mysqli_close($con);
?>
As #ali already said you need to check for user existence an then go ahead and create it:
/* Connect to the DB using MySQLi class */
$mysql = new mysqli('localhost', 'user', 'password', 'database');
/* If an error code is reported... */
if($mysql->connect_errno)
{
echo json_encode(array(
'query_result' => 'ERROR'
));
}
/* Otherwise go ahead... */
else
{
/* Prepare a select statement to check user existence */
$selectStmt = $mysql->prepare("SELECT * FROM `users10` WHERE `phone` = ? OR `email` = ?");
/* Retrieve arguments */
$fullName = $_GET['fullname'];
//$userName = $_GET['username'];
$passWord = $_GET['password'];
$phoneNumber = $_GET['phonenumber'];
$emailAddress = $_GET['emailaddress'];
/* Binding parameters */
$selectStmt->bind_param('ss', $phoneNumber, $emailAddress);
/* Execute statement */
if (!$selectStmt->execute()) {
echo json_encode(array(
'query_result' => 'ERROR'
));
}
else
{
/* If the number of returned rows is 0 */
if(0 === $selectStmt->get_result()->num_rows)
{
$insertStmt = $mysql->prepare("INSERT INTO `users10` (`fullname`, `password`, `phone`, `email`) VALUES (?, ?, ?, ?)");
$insertStmt->bind_param('ssss', $fullName, $passWord, $phoneNumber, $emailAddress);
/* Try to insert the new user */
if (!$insertStmt->execute()) {
echo json_encode(array(
'query_result' => 'FAILURE'
));
}
else
{
echo json_encode(array(
'query_result' => 'SUCCESS'
));
}
}
else
{
echo json_encode(array(
'query_result' => 'FAILURE'
));
}
}
}
I think you need ' ON DUPLICATE KEY UPDATE '
this will update a given record when it is present, but insert a new one if not.
on duplicate key
I know how to send data using volley library and get those from php. Problem is, I want to send a Json String and decode those data from the php side.
This is the method I am using to send data using param. Last item is the json String
private void checkOrderNo() {
pDialog.setMessage("Sending...");
showDialog();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
final String nowDate = df.format(new Date());
//final day of the month
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
final String lastDate = sdf.format(lastDayOfMonth);
Log.d("Last day ", sdf.format(lastDayOfMonth) + " // Today" + nowDate);
// Tag used to cancel the insert
String tag_string_req = "req_insert";
final StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_ITEM_DETAILS_SEND, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
if (jObj.names().get(0).equals("found")) {
newOrderId = jObj.getString("found").toString();
orderIdForItemTable = newOrderId;
Log.d(TAG, "newOrderId: " + newOrderId);
Log.d(TAG, "New repID 2 inserted into sqlite: " + newOrderId + " " + nowDate);
sqLiteHandler.addItemDetails(newOrderId, repID, dealerID, nowDate, lastDate, selectedDisChannel);
finish();
Bundle basket = new Bundle();
basket.putString("dealerName", dealerName);
basket.putString("orderNo", newOrderId);
basket.putString("jsonString", json_string);
Intent intent = new Intent(SelectItem.this, ItemCart.class);
intent.putExtras(basket);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalied Request", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Inserting Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("order_no", orderId);
params.put("repID", repID);
params.put("dealerID", dealerID);
params.put("nowDate", nowDate);
params.put("lastDate", lastDate);
params.put("disChannel", selectedDisChannel);
params.put("jsonString", json_string);
return params;
}
};
strReq.setRetryPolicy(new DefaultRetryPolicy(15000, 1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
This is my PhP for volley
<?php
require_once 'include/Config_test.php';
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("connection failed");
mysql_select_db(DB_DATABASE,$con) or die("db selection failed");
$order_no = $repID = $dealerID = $nowDate = $jsonString = $lastDate = $disChannel = "";
if(isset($_POST['order_no'])){
$order_no = $_POST['order_no'];
$repID = $_POST['repID'];
$dealerID = $_POST['dealerID'];
$nowDate = $_POST['nowDate'];
$lastDate = $_POST['lastDate'];
$disChannel = $_POST['disChannel'];
$jsonString= $_POST['jsonString'];
}
$result = mysql_query("SELECT MAX(order_no) FROM tbl_items_header_t");
$row = mysql_fetch_row($result);
if($row[0] < 70000000){
$highest_id = 70000000;
} else{
$highest_id = $row[0] + '1';
}
//$highest_id = $row[0] + '1';
$query = mysql_query("INSERT INTO tbl_items_header_t(order_no,rep_no,dealer_no,order_date,last_date,dis_channel,status)
VALUES('$highest_id','$repID','$dealerID','$nowDate','$lastDate','$disChannel','')");
$json['found']= $highest_id;
echo json_encode($json);
?>
I know send json String using DefaultHttpClient but it is deprecated. I have to use two PHP also. I want to do it using volley.
This is what I use for get json String using DefaultHttpClient. It worked. But I want to use this in the volley.
<?php
require_once 'include/Config_test.php';
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("connection failed");
mysql_select_db(DB_DATABASE,$con) or die("db selection failed");
$postdata = file_get_contents('php://input');
$data = json_decode($postdata, true);
if (is_array($data['sending_items'])) {
foreach ($data['sending_items'] as $record) {
$order_no = $record['order_no'];
$items = $record['items'];
$items_no = $record['items_no'];
$plant = $record['plant'];
$quantity = $record['quantity'];
mysql_query("INSERT INTO tbl_item_list(order_no, items, items_no, plant, quantity) VALUES('$order_no', '$items', '$items_no', '$plant', '$quantity')");
}
}
echo json_encode($data);
mysql_close($con);
?>
What I want is that when someone(user) click's a button on main activity two values will be send to the php file with the help of volley POST request, say minvalue and maxvalue, and it will select the data accordingly from mysql database.
Here's my code for POST request:
public void FilterPower(View view) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
/*Some Method*/
/*Display data in recyclerview*/
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
listSuperHeroes = new ArrayList<>();
//Calling method to get data
getData();
/*End Display data in recyclerview*/
/*End Some Method*/
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String,String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("minvalue", "1000");
params.put("maxvalue", "2000");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}
}
My Php File Code:
<?php
$con = mysqli_connect("127.0.0.1","superinfoadmin","","superhero");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if($_SERVER['REQUEST_METHOD']=='POST'){
$minvalue = $_POST['minvalue'];
$maxvalue = $_POST['maxvalue'];
$result = mysqli_query($con, "SELECT * FROM superinfo, publisher WHERE superinfo.s_publisherid=publisher.p_id AND (s_power BETWEEN $minvalue AND $maxvalue)");
//$result = mysqli_query($con, "INSERT INTO testDB (min, max) VALUES ('$minvalue', '$maxvalue')");
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysqli_close($con);
}
?>
When I try running my app using above code no data is selected and displayed in recyclerview.
But when I try Inserting values in the database using same variable then the values are inserted.
I even tried keeping both select and insert statement to check whether it enters the "IF" loop, and yes it does enters and insert the values in DB but does not executes select statement.
However if I give an else statement to select all data and display it in recyclerview it works properly, so there's no problem in displaying the data in recyclerview the code works fine. Below is the same PHP code with else statement:
if($_SERVER['REQUEST_METHOD']=='POST'){
$minvalue = $_POST['minvalue'];
$maxvalue = $_POST['maxvalue'];
$result = mysqli_query($con, "SELECT * FROM superinfo, publisher WHERE superinfo.s_publisherid=publisher.p_id AND (s_power BETWEEN $minvalue AND $maxvalue)");
//$result = mysqli_query($con, "INSERT INTO testDB (min, max) VALUES ('$minvalue', '$maxvalue')");
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysqli_close($con);
}
else{
$result = mysqli_query($con, "SELECT * FROM superinfo, publisher WHERE superinfo.s_publisherid=publisher.p_id");
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysqli_close($con);
}
Please Help I don't know what I'm doing wrong or what I'm not doing.
I don't see any problem in your code but check this if you get any output please inform me
<?php
$con = mysqli_connect("127.0.0.1","superinfoadmin","","superhero");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if($_SERVER['REQUEST_METHOD']=='POST'){
$minvalue = $_POST['minvalue'];
$maxvalue = $_POST['maxvalue'];
$sql="SELECT * FROM superinfo, publisher WHERE
superinfo.s_publisherid=publisher.p_id AND s_power BETWEEN '$minvalue' AND
'$maxvalue'";
echo $sql;
$result = mysqli_query($con,$sql);
$output=array();
$output = mysqli_fetch_assoc($result);
print(json_encode($output));
mysqli_close($con);
}
?>