PHP MYSQL查询使用Ajax数据返回null,但不返回硬编码数据

I have the following PHP script:

include("dbconnecti.php");
$cropId = $_POST['cropId'];
//echo 'the id is: ' . $cropId;

$query = "SELECT W.*,FI.*, PN.*, CONCAT(FI.fName, ' ', FI.lname) AS farmer  
          FROM `wantToSell` AS W, `produceName` AS PN, `farmerInfo` AS FI 
          WHERE W.farmerId = FI.farmerId AND W.produceId = PN.produceId AND W.produceId = '" . $cropId ."'";

$result = $dbconnect->query($query); 
if($result){
  while($row = $result->fetch_assoc()){
    $allRows[] = $row;
  }
  echo json_encode($allRows);
 }
 else{
   echo json_encode($dbconnect -> error);
   die;
 }
}

And JQuery script:

function cropDescrip(clicked_id) {
  $.ajax({
    url : "../php/cropdescrip.php",
    type : "POST",
    dataType : 'JSON',
    cache : false,
    data : {cropId : clicked_id},
    success : function (data) {
      console.log(data);
    } //end success
  }); //end ajax
} //end cropDescrip

If I replace $_POST[cropId] with a actual value (e.g. tmt001) the query statement returns a valid result. But when I pass a value to $_POST[cropId] via a jQuery Ajax call, the SQL query returns an empty set.

The echo statement shows that the value is being passed to the PHP script.

What is happening, and how do I fix it?

Perhaps it would be best to change your code to use a prepared statement. It might solve your problem as well as removing your sql injection risk. Something like this:

$stmt = $mysqli->prepare("SELECT W.*,FI.*, PN.*, 
      CONCAT(FI.fName, ' ', FI.lname) AS farmer  
      FROM `wantToSell` AS W, `produceName` AS PN, `farmerInfo` AS FI 
      WHERE W.farmerId = FI.farmerId AND W.produceId = PN.produceId AND W.produceId =?";

/* assuming cropId is a string given your quotes in the original */
$stmt->bind_param("s", $cropId);

/* execute query */
$stmt->execute();

$result = $stmt->get_result();

Just guessing here, but it looks like you're passing the clicked_id of the element, and not the value of that element. Try this from your jQuery code:

function cropDescrip(clicked_id) {
  $.ajax({
    url : "../php/cropdescrip.php",
    type : "POST",
    dataType : 'JSON',
    cache : false,
    data : {cropId : $("#" + clicked_id).val()},  // <-- HERE
    success : function (data) {
      console.log(data);
    } //end success
  }); //end ajax
} //end cropDescrip

This will find the element with the id, using element_id as the selector value. It will capture the value of that element, and pass it through the cropId key to the PHP server.

If this doesn't work as-is, it would be very useful to know precisely what clicked_id actually is (show the HTML and Javascript code for it), and what value is being passed to the PHP server in $_POST[cropId].