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

I'm trying to pass a string of data from a field which is separated by commas via ajax to a php file which does a simple search.

The data I am passing for example is: var dataString = '1,2,3,4' as post. I'm now trying to get the value in my PHP file and make a query to my database but the dataString post value is empty once it gets into the PHP file. Can anyone explain where I'm wrong here?

Also, is there a better way to generate my SQL query?

Code:

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;
}

You need to specify an object to $.ajax for the data parameter, if you specify a string (as you have done) it is assumed to be a query string. So change your AJAX call to

  $.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);
    }
  });

Also, in your PHP, immediately after the if(isset($_POST['dat'])){ you need to change

$dat = $_POST['img'];

to

$dat = $_POST['dat'];

In terms of generating your SQL query, your current method leaves you open to SQL injection. I would do something like this:

$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 .= ")";

Then you can bind the type values at the same time as you bind :loc.