Treps
Treps

Reputation: 800

UPDATE MySQL with JQuery sortable new value

Question: How can I UPDATE my MySQL-database with the new value from a JQuery sortable list?

This is my code this far:

<?php

echo '
<form action="" method="post"> 
<ul id="sortable">';

$array = str_split("ABCDEFGHI", 3);

for($i = 0; $i < count($array); $i++) {
  echo '
    <li class="ui-state-default">
    <span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' . $array[$i] . '<input type="hidden" name="pos[]" value="'.$array[$i].'">
    </li>';
}

echo '
</ul><br>

<input type="submit" name="submit" value="Show order">
</form>

</body>
</html>';

if(isset($_POST['submit'])) {
    foreach($_POST['pos'] as $value){
        echo $value;
    }

}

?>

Information:

$value holds the new value from JQuery sortable list that I want to UPDATE my MySQL-database with. But can't be used outside foreach. So how can I do it? I know I can make a variable that holds the SQL-query (in foreach) like this:

$query ="UPDATE test SET order='" . $value . "' WHERE id='" . $random_function . "'";

But how do I use the variable $query to perform the actual SQL-query?

$_POST['pos'] array-structure:

Array ( [0] => ABC [1] => DEF [2] => GHI ) Array ( [0] => ABC [1] => DEF [2] => GHI ) Array ( [0] => ABC [1] => DEF [2] => GHI )

Upvotes: 0

Views: 380

Answers (2)

Sibiraj PR
Sibiraj PR

Reputation: 1481

Try this .

$str = '';
if(isset($_POST['submit'])) {
  foreach($_POST['pos'] as $value){
    $str = $str.$value;
  }
 }

$query ="UPDATE test SET order='" . $str . "' WHERE id='" . $random_function . "'";
mysql_query($query);

Upvotes: 1

dikirill
dikirill

Reputation: 1903

I'm doing it like this:

in JavaScript

var ids = [];
rows.each(function (index, value)
{
    ids.push($(value).attr("data-item-id"));
});
$.post('/url/to/save/order/, {orderMap:JSON.stringify(ids)}, function() {}, 'json');

in PHP:

$orderMap = json_decode(stripslashes($this->getPost("orderMap")));
$statements = array();
foreach ($orderMap as $itemId => $position) {
    $statements[] = sprintf("UPDATE `{$tableName}` SET `{$fieldName}`=%d WHERE `{$fieldIdName}`=%d", $position, $itemId);
}
$this->db->executeMultiQuery(implode(";", $statements));

Upvotes: 1

Related Questions