Update with Multidimensional Array

-3

I have a terrible problem, I can not update mysql via PDO, with array coming from some form fields. I've tried a lot and so far I can not do the update. The array comes in this format.

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
            [5] => 6
            [6] => 7
            [7] => 8
            [8] => 9
            [9] => 10
        )

    [url] => Array
        (
            [0] => /ckfinder/userfiles/images/2141.jpg
            [1] => rty
            [2] => rtyrcial.jpg
            [3] => rtyrtrfiles/images/3.jpg
            [4] => rtyrimages/especial.jpg
            [5] => rtyrfiles/images/especial.jpg
            [6] => rtyres/images/especial.jpg
            [7] => /ckfinder/userfiles/images/3.jpg
            [8] => /ckfinder/userfiles/images/Capa1.jpg
            [9] => asd
        )

)

TABLE (example data):

SQL (PDO):

UPDATE via_imagens SET img_url = array[url] WHERE img_capa IS NULL AND img_id = array[id]

Okay, so it goes like this:

$db = new PDO('mysql:host=localhost;dbname=test', 'root', '');

$sql = 'UPDATE via_imagens SET img_url = ? WHERE img_capa IS NULL AND img_id = ?'; 

$stmt = $db->prepare($sql);

foreach($dados as $item ){
  $stmt->execute(array($dados['url'], $dados['id']));
}

    

asked by anonymous 01.06.2015 / 21:09

1 answer

0

The simplest way to do this is to get the values from the array pass them by a for and execute the update inside it. If you need something more restrictive you can have a transaction to ensure the integrity of the operation.

  

Notice: Array to string conversion

It happens when you try to print an array value where the index call is not correct, what will happen is to write the Array value in the database.

Starting from the point that your array is in a variable called $lista your access should be done like this: $lista['url'][1] will display the rty value, the 1 index must be change a counter ( $i for example ).

$dados = array(); //esse array é tem a url e o id da sua tabela no exemplo

$db = new PDO('mysql:host=localhost;dbname=teste', 'usuario', 'senha');

$sql = 'UPDATE via_imagens SET img_url = ? WHERE img_capa IS NULL AND img_id = ?';
$stmt = $db->prepare($sql);

$total_itens = count($dados['id']);

for($i=0; $i<$total_itens; $i++){
   $stmt->execute(array($dados['url'][$i], $dados['id'][$i]));
}
    
01.06.2015 / 22:35