访问从 stringRequest 发送的数据

Access data sent from stringRequest

我正在尝试访问从此处的 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);
}

我在这里尝试访问我的 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";
    }
}

查询成功 运行 但在 user_id 和 product_id 位置插入 0。

我做错了什么?

提前致谢!

谨防SQL注入!使用 prepared statements 保护您的数据库。


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

$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();