Java 访问从stringRequest发送的数据

Java 访问从stringRequest发送的数据,java,php,android,android-studio,android-volley,Java,Php,Android,Android Studio,Android Volley,我正在尝试访问从stringRequest发送的数据: public class ProductDetailActivity extends AppCompatActivity { String cart_url = "http://192.168.1.15/AndroidAppDatabaseConnection/add_to_cart.php"; String favorites_url = "http://192.168.1.15/AndroidAppData

我正在尝试访问从stringRequest发送的数据:

public class ProductDetailActivity extends AppCompatActivity {
String cart_url = "http://192.168.1.15/AndroidAppDatabaseConnection/add_to_cart.php";
String favorites_url = "http://192.168.1.15/AndroidAppDatabaseConnection/add_to_favorites.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_product_detail);
    Intent intent = getIntent();
    String imageUrl = intent.getStringExtra(EXTRA_URL);
    String email = intent.getStringExtra("user");
    final int product_id = intent.getIntExtra(EXTRA_ID, 0);
    String name = intent.getStringExtra(EXTRA_NAME);
    Double price = intent.getDoubleExtra(EXTRA_PRICE, 0);
    String description = intent.getStringExtra(EXTRA_DESCRIPTION);
    ImageView imageView = findViewById(R.id.image_view);
    TextView textViewName = findViewById(R.id.text_view_name);
    TextView textViewPrice = findViewById(R.id.text_view_price);
    TextView textViewDescription = findViewById(R.id.text_view_description);
    Button add_cart = findViewById(R.id.add_cart);
    Button add_favorites = findViewById(R.id.add_wishlist);
    add_cart.setTag(email);
    textViewName.setText(name);
    textViewPrice.setText(price + "€");
    textViewDescription.setText(description);
    add_cart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String email = view.getTag().toString();
            add_to_cart(email, product_id);
        }
    });
    add_favorites.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            add_to_favorites();
        }
    });
}
private void add_to_cart(final String e, final int id) {
    JSONObject jsonBody = new JSONObject();
    try {
        jsonBody.put("user", e);
        jsonBody.put("product", id);
        final String requestBody = jsonBody.toString();
    } catch (JSONException ex) {
        ex.printStackTrace();
    }
    StringRequest stringRequest = new StringRequest(Request.Method.POST, cart_url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("VOLLEY", response);
            Toast.makeText(ProductDetailActivity.this,"successfully Add Into Cart",Toast.LENGTH_SHORT).show();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(ProductDetailActivity.this, "Could not add item into cart", Toast.LENGTH_SHORT).show();
        }
    }){
        @Override
        public Map<String, String> getParams() {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("user", e);
            params.put("product", String.valueOf(id));
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
private void add_to_favorites() {
    StringRequest stringRequest = new StringRequest(Request.Method.POST, favorites_url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Toast.makeText(ProductDetailActivity.this, "Successfully added into Favorites", Toast.LENGTH_SHORT).show();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(ProductDetailActivity.this, "Could not add item into favorites", Toast.LENGTH_SHORT).show();
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
        }
    };
   RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
公共类ProductDetailActivity扩展了AppCompatActivity{
字符串cart_url=”http://192.168.1.15/AndroidAppDatabaseConnection/add_to_cart.php";
字符串收藏夹\u url=”http://192.168.1.15/AndroidAppDatabaseConnection/add_to_favorites.php";
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u product\u detail);
Intent=getIntent();
String imageUrl=intent.getStringExtra(额外URL);
字符串email=intent.getStringExtra(“用户”);
最终int product_id=intent.getIntExtra(额外的_id,0);
字符串名称=intent.getStringExtra(额外名称);
Double price=intent.getDoubleExtra(额外价格,0);
字符串描述=intent.getStringExtra(额外描述);
ImageView ImageView=findViewById(R.id.image\u视图);
TextView textViewName=findViewById(R.id.text\u view\u name);
TextView textViewPrice=findViewById(R.id.text\u view\u price);
TextView textViewDescription=findViewById(R.id.text\u view\u description);
按钮add\u cart=findviewbyd(R.id.add\u cart);
按钮add\u favorites=findViewById(R.id.add\u wishlist);
添加购物车设置标签(电子邮件);
textViewName.setText(名称);
textViewPrice.setText(价格+“€”);
textViewDescription.setText(说明);
添加\u cart.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
字符串email=view.getTag().toString();
将\添加到\购物车(电子邮件、产品\ id);
}
});
添加\u收藏夹.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
将_添加到_收藏夹();
}
});
}
私有无效添加到购物车(最终字符串e,最终整数id){
JSONObject jsonBody=新的JSONObject();
试一试{
jsonBody.put(“用户”,e);
jsonBody.put(“产品”,id);
最后一个字符串requestBody=jsonBody.toString();
}捕获(JSONException ex){
例如printStackTrace();
}
StringRequest StringRequest=newStringRequest(Request.Method.POST、cart\uURL、new Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
Log.i(“截击”,回应);
Toast.makeText(ProductDetailActivity.this,“成功添加到购物车”,Toast.LENGTH_SHORT.show();
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(ProductDetailActivity.this,“无法将项目添加到购物车”,Toast.LENGTH_SHORT.show();
}
}){
@凌驾
公共映射getParams(){
HashMap params=新的HashMap();
参数put(“用户”,e);
参数put(“产品”,字符串.valueOf(id));
返回参数;
}
};
RequestQueue RequestQueue=Volley.newRequestQueue(this);
添加(stringRequest);
}
私有无效添加到收藏夹(){
StringRequest StringRequest=新的StringRequest(Request.Method.POST、收藏夹\u url、新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
Toast.makeText(ProductDetailActivity.this,“成功添加到收藏夹”,Toast.LENGTH_SHORT.show();
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(ProductDetailActivity.this,“无法将项目添加到收藏夹”,Toast.LENGTH\u SHORT.show();
}
}){
@凌驾
公共映射getHeaders()引发AuthFailureError{
HashMap headers=新的HashMap();
headers.put(“内容类型”、“应用程序/json;字符集=utf-8”);
返回标题;
}
};
RequestQueue RequestQueue=Volley.newRequestQueue(this);
添加(stringRequest);
}
在这里,我尝试访问PHP文件中的数据:

<?php
include_once "database_connect.php";
$email = $_POST["user"];
$product_id = $_POST["product"];
$sql = "SELECT * FROM users WHERE email = '$email';";
$result= mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
$user_id = $row['user_id'];
$count=mysqli_num_rows($result);
if($count>0){ /*if product is already in cart */
    echo "Product already in cart";
}
else {
    $add_to_cart="INSERT INTO cart (user_id,product_id,quantity) VALUES ('$user_id','$product_id','1')";
    if(!mysqli_query($conn,$add_to_cart))
    {
        echo "Can't add product to cart";
    }
    else
    {
        echo "Product successfully added to cart";
    }
}

小心SQL注入!用于保护数据库


要检查特定用户的购物车中是否已经有产品,您可以将第一个sql查询更改为以下内容(以准备好的语句编写):


您的查询(对SQL注入开放)与购物车中的项目没有关系。因此,
if($count>0){/*if产品已经在购物车中了*/
是不正确的。您最终解决了问题吗?我确实解决了@Ivan86,谢谢您的帮助。
$conn = new mysqli($servername, $username, $password, $dbname);

$stmt = $conn->prepare("SELECT c.quantity FROM cart c
                       JOIN users u ON u.user_id = c.user_id
                       WHERE c.product_id = ? AND u.email = ?");

$stmt->bind_param("is", $product_id, $email);
// 'i' means integer and 's' means string
$stmt->execute();
$stmt->store_result();

if($stmt->num_rows > 0) {
    // product exists in cart
}

$stmt->close();