php—使用逗号分隔的ajax数据构建sql查询以搜索表

sqyvllje  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(343)

我试图通过ajax将一个由逗号分隔的字段中的一串数据传递给一个php文件,该文件执行简单的搜索。
例如,我传递的数据是: var dataString = '1,2,3,4' 作为 post . 我现在正试图从我的生活中得到价值 PHP 文件并对我的数据库进行查询,但 dataString post值一旦进入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;
}
csbfibhn

csbfibhn1#

你需要指定一个对象 $.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 .

相关问题