0

So I am trying to send the "id" of a selected row in datatable in javascript to a php page so I could delete it from database.

var ids = $.map(table.rows('.selected').data(), function (item) {
    return item[0]  });

the variable "ids" is sent by post method

$.post( "deleterow.php", { v1: ids });

but it didn't worked so i try to see the response from post method and it says "notice array to string conversion in C on line ... " the line is of php page where i am writing the delete query

$id = $_POST["v1"];
$query = "DELETE FROM `package` WHERE `id` = '$id'";

The whole php page works fine when trying with other values.

  • You are sending an array (`map` returns an array) to your PHP page, and then you're trying to concatenate it with a string, which doesn't seem to work. – Serge K. Jul 26 '17 at 08:04

1 Answers1

3

Because you send an array here:

$.post( "deleterow.php", { v1: ids });

so v1 contains an array of elements. But in your php code you treat it as a single element:

$id = $_POST["v1"];

Hence the notice array to string conversion.

If you send an array of elements, you have to get it as an array and treat is as an array. To create a correct SQL string you should append each ID, like this:

$ids = json_decode($_POST["v1"]);
$query = "DELETE FROM `package` WHERE";
$first = true;
foreach ($ids as $id) {
    if ($first) {
        $first = false;
    } else {
        $query += " OR";
    }
    $query += " `id` = '$id'"
}

This way you loop the array and append a id = ID for each array element.

Now, this is important, this code is prone to SQL injection, a really bad security problem. Read this to get more info about this: How can I prevent SQL injection in PHP?

Jorge Fuentes González
  • 11,568
  • 4
  • 44
  • 64