2017-04-03 34 views
0

我无法使用数组来使sql查询一次删除多行数据。请忽略我现在正在使用sql注入。如何使用PHP中的ID数组删除多行mysql

编辑:一个更好的解释 - 我的PHP不工作。我有所修改它,检查中给予

注意链接塞巴斯蒂安后:我使用AngularJS发布

这是我的$的数据结构,从我controller.js功能。 devicesToDelete只是一个简单的数组,例如[“1”,“2”,“3”]:

$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete }) 
    .success(function(data) { 
      $scope.results = data; 
      devicesToDelete = []; 
    }) 
    .error(function(err) { 
     $log.error(err); 
    }) 

这是更新后的php代码,有问题。在点击我的deleteMultiple按钮,只有确认警报触发时,选择的项目不会被删除,并且控制台是明确的错误:

<?php 

$data = json_decode(file_get_contents("php://input")); 

include('config.php'); 

$sql = "DELETE FROM devices WHERE devID in (implode(",", $data))"; 

$qry = $conn->query($sql); 

$sql = "SELECT * FROM devices"; 

$qry = $conn->query($sql); 

$data = array(); 

if($qry->num_rows > 0){ 
    while($row = $qry->fetch_object()){ 
     $data[] = $row; 
    } 
}else { 
    $data[] = null; 
} 




$conn->close(); 

echo json_encode($data); 

编辑2:我设法解决我自己的问题。这里是解决方案:

我使用。加入()我上的JavaScript侧阵列上有所有要删除的ID用逗号分隔的(例如,1,2,3):

$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete.join(", ") }) 
        .success(function(data) { 
         $scope.results = data; 
         devicesToDelete = []; 
        }) 
        .error(function(err) { 
         $log.error(err); 
        }) 

然后,我只是说我完全看了一眼在我的PHP代码这是我经过了进去数组的名字 - devicesToDeleteArray

<?php 

$data = json_decode(file_get_contents("php://input")); 

include('config.php'); 

$sql = "DELETE FROM devices WHERE devID in ($data->devicesToDeleteArray)"; 

$qry = $conn->query($sql); 

$sql = "SELECT * FROM devices"; 

$qry = $conn->query($sql); 

$data = array(); 

if($qry->num_rows > 0){ 
    while($row = $qry->fetch_object()){ 
     $data[] = $row; 
    } 
}else { 
    $data[] = null; 
} 

$conn->close(); 

echo json_encode($data); 
+5

您应该避免使用循环中的SQL,不惜任何代价。要解决你的WHERE IN问题,请看看这里:[http://stackoverflow.com/questions/2373562/pdo-with-where-in-queries] – Sebastian

+0

你有什么困难?你应该使用'.then'来代替'success'和'error' – Akashii

+1

如果这是你的工作功能......你真正的问题是什么......? .. 没有结果 ?错误的结果? ..explain better .. – scaisEdge

回答

0

这里的PHP代码:

<?php 
$ids = $_POST['devicesToDeleteArray']; 
if(!is_array($data)) { 
    $ids = json_decode($data, true); 
} 
if(!empty($ids)) { 
include 'config.php'; 

$sql = "DELETE FROM devices WHERE devID in (implode(",", $ids))"; 
$qry = $conn->query($sql); 
$sql = "SELECT * FROM devices"; 
$qry = $conn->query($sql); 
$data = array(); 
if ($qry->num_rows > 0) { 
    while ($row = $qry->fetch_object()) { 
     $data[] = $row; 
    } 
} else { 
    $data[] = null; 
} 
$conn->close(); 
echo json_encode($data); 
相关问题