qadenza
qadenza

Reputation: 9293

How to update database using arrays?

<div data-id=1448 class='item folder'>lorem ipsum</div>
<div data-id=1393 class='item folder'>lorem ipsum</div>
<div data-id=1441 class='item folder'>lorem ipsum</div>
<div data-id=1442 class='item folder'>lorem ipsum</div>

js

$('#mpsave').click(function(){
    var ids = [];
    var indexes = [];
    $('.folder').each(function(){
        ids.push($(this).data('id'));
        indexes.push($(this).index());
    });
    console.log(ids);  // works well
    console.log(indexes);  // works well

$.ajax({
    url: 'target.php',
    type: 'post',
    data: {'ids' : ids, 'indexes' : indexes},
    success: function(data){
        console.log(data); // works well
    }
});
});

target.php

extract($_POST);

print_r($ids);
print_r($indexes);

So, arrays are on php side. Now, I need to update database this way:
- for each ids element find the corresponding row
- update the row (column inde) with value of parallel indexes element.

Something like this:

try {
$stmt = $db->prepare("UPDATE folders SET inde = :inde WHERE id = :id");
$stmt->execute(array(
    ":id" => $ids-element,
    ":inde" => $indexes-element
));
}
catch(PDOException $e) {
echo $e->getMessage();
}

Any help?

Upvotes: 1

Views: 36

Answers (1)

Patrick Michaelsen
Patrick Michaelsen

Reputation: 1045

Can you even use hyphens in php variable names? Try:

    for ($i = 0; $i <= count($ids); $i++){
            try {
                $stmt = $db->prepare("UPDATE folders SET inde = ? WHERE id = ?");
                $stmt->bind_param("ii",$ids[i],$indexes[i]);
                $stmt->execute();
            }
            catch(PDOException $e) {
                echo $e->getMessage();
            }
     }

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php http://php.net/manual/en/mysqli-stmt.bind-param.php

Upvotes: 1

Related Questions