0

I am a bit stuck and also new in this topic. I want to delete certain elements in a SQL table. The entries to delete are stored in an array. Usually its done with the commaned DELETE FROM table where id in (1,2,3,4);. But as soon as I insert my array I receive the error "Array to string conversion". I am bit lost as I do not use any strings.

Thats my delete statement, please ignore SQL injection for now.

  $checkIndexes = $_POST['checkIndexes'];
  print_r($checkIndexes);
        
  $deleteProperty = "
     BEGIN TRANSACTION [deleteProperty]
     BEGIN TRY
        DELETE FROM eigenschaften WHERE id IN ('$checkIndexes');
        COMMIT TRANSACTION [deleteProperty];
     END TRY
     BEGIN CATCH
        ROLLBACK TRANSACTION [deleteProperty]
     END CATCH
  ";
  if (!sqlsrv_query($connection, $deleteProperty)) {
     die (print_r(sqlsrv_errors(), true));
  }
Zhorov
  • 28,486
  • 6
  • 27
  • 52
ICoded
  • 319
  • 3
  • 18
  • 1
    You do not have SQL injection. You will have, if you use `DELETE FROM eigenschaften WHERE id IN ('$checkIndexes');`. An approrpiate solution here is to use `sqlsrv_prepare` and `sqlsrv_execute` with proper binding. – Zhorov Oct 18 '21 at 07:33
  • As I mentioned, not important for now. The code is still not running because of the metnioned problem. – ICoded Oct 18 '21 at 07:35
  • 1
    `Array to string conversion` is a PHP notice. `DELETE FROM eigenschaften WHERE id IN ('checkIndexes');` do not use `$checkIndexes` variable (as you probably expect). Which PHP line gives this error message? – Zhorov Oct 18 '21 at 07:39
  • Exact the delete statement line does, DELETE FROM eigenschaften WHERE id IN ('$checkIndexes'); I missed the $ char, I updated the question. Still not working as it throws this error. – ICoded Oct 18 '21 at 07:46
  • 1
    First of all, you need to rewrite the code using the [sqlsrv_begin_transaction](https://www.php.net/manual/en/function.sqlsrv-begin-transaction.php) function as shown in the example at the provided link. – id'7238 Oct 18 '21 at 07:50
  • @id'7238 I go a transaction code around, I only post the snippet in the question. Still thanks for mentioning. :) – ICoded Oct 18 '21 at 07:53
  • @Zhorov thanks it works partly, unfortunately only with one item. As soon as the array contains more than one item nothing is happening, no error no execution. Just the print_r – ICoded Oct 18 '21 at 07:54
  • @Zhorov now it works, I do the implode command before and add only the variable without any further chars. Thanks al lot. – ICoded Oct 18 '21 at 07:58
  • 1
    My mistake. You need to convert the array to string: `DELETE FROM eigenschaften WHERE id IN (" . implode(",", $checkIndexes) . ")`;. Again, use a parameterized query. – Zhorov Oct 18 '21 at 07:58
  • 3
    ... and then do something like this: [Parameterising an IN clause in PHP with sqlsrv](https://stackoverflow.com/a/64964406/14717238) – id'7238 Oct 18 '21 at 08:00

0 Answers0