使用分隔到搜索表的Ajax数据逗号构建SQL查询

时间:2018-10-06 07:30:36

标签: php jquery mysql ajax

我正在尝试通过ajax将以逗号分隔的字段中的数据字符串传递给一个进行简单搜索的php文件。

例如,我要传递的数据是:var dataString = '1,2,3,4'post。我现在正在尝试获取PHP文件中的值并查询数据库,但是dataString后的值在进入PHP文件后为空。谁能解释我在哪里错了?

还有,还有更好的方法来生成我的SQL查询吗?

代码:

var dataString = "1,2,3,4";

      $.ajax({ /* THEN THE AJAX CALL */
        type: "POST", /* TYPE OF METHOD TO USE TO PASS THE DATA */
        url: "includes/search.php", /* PAGE WHERE WE WILL PASS THE DATA */
        data: dataString, /* THE DATA WE WILL BE PASSING */
        success: function(result){ /* GET THE TO BE RETURNED DATA */
         alert(result);
        }
      });

** PHP **

if(isset($_POST['dat'])){
    $dat = $_POST['img'];
    $types = explode(",", $dat);
    $size = sizeof($types);

    $loc = '30';

    $ini = $types[0];

    $query = "SELECT `location_images`.`image_link` FROM `location_images` INNER JOIN `image_type` ON `location_images`.`id` = `image_type`.`image_id` WHERE `location_images`.`location_id` = :loc AND (`image_type`.`dt_id` = '".$ini ."'";

    for($i=1; $i<$size; $i++){
        $query .= " OR `image_type`.`dt_id` = '".$types[$i]."'";
    }

    $query .= ")";
    echo $query; die;
}

1 个答案:

答案 0 :(得分:1)

您需要为数据参数指定$.ajax的对象,如果您指定了一个字符串(如前所述),则假定该字符串为查询字符串。因此,将您的AJAX调用更改为

  $.ajax({ /* THEN THE AJAX CALL */
    type: "POST", /* TYPE OF METHOD TO USE TO PASS THE DATA */
    url: "includes/search.php", /* PAGE WHERE WE WILL PASS THE DATA */
    data: { dat: dataString }, /* THE DATA WE WILL BE PASSING */
    success: function(result){ /* GET THE TO BE RETURNED DATA */
     alert(result);
    }
  });

此外,在您的PHP中,if(isset($_POST['dat'])){之后,您需要更改

$dat = $_POST['img'];

$dat = $_POST['dat'];

就生成SQL查询而言,当前方法使您可以进行SQL注入。我会做这样的事情:

$query = "SELECT `location_images`.`image_link` 
          FROM `location_images` 
          INNER JOIN `image_type` ON `location_images`.`id` = `image_type`.`image_id` 
          WHERE `location_images`.`location_id` = :loc AND
               (`image_type`.`dt_id` = :type0";
for ($i = 1; $i < $size; $i++) {
    $query .= " OR image_type`.`dt_id` = :type$i";
}
$query .= ")";

然后,您可以在绑定:loc的同时绑定类型值。