duanpei4455 2016-06-04 01:40
浏览 45

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?

  • 写回答

2条回答 默认 最新

  • doujin8673 2016-06-04 01:57
    关注

    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();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)