开发者

Jquery append/Remove and saving to database

I was wondering if anyone could take a look at this code and help me come up with a better way to do this if there is one.

I am using jQuery append/remove to add and remove list items. My code first selects any existing rows from the db and displays those in the list, and then the user can add or remove any elements from the list.

I have a database structure similar to this:

object_id  element_id   auto   order
   1          1          0       2
   1          2          0       1
   1          3          1       3

After users have finished appending/remove I will be left with html code similar to this:

<ul id="element-list" class="ui-sortable"><li>
<label for="element">Element Description</label>
<input type="hidden" value="1" name="element[1][id]">
<input type=开发者_如何学编程"checkbox" value="" name="element[1][auto]">
</li>

<li>
<label for="element">Element Description</label>
<input type="hidden" value="2" name="element[2][id]">
<input type="checkbox" value="" name="element[2][auto]">
</li>
</ul>

As users can add and remove elements including rows which exist in the database I am puzzled about how it is best to save these changes in the database. Currently I am deleting all corresponding rows then inserting new rows inside a loop as follows:

foreach($_POST['element'] as $element){

$auto = (isset($element["auto"])) ? 1 : 0;

$query="INSERT INTO $table (object_id, element_id, auto) VALUES ('".$object_id."', '".$element["id"]."', '".$auto."') ";
}

I am wondering if there is a more efficient way to do this than deleting all rows then inserting new ones?

Any input would be appreciated.

Thanks

Paul


That's definitely the easiest way to do it.

2 suggestions...

  1. Use PDO or mysqli with prepared queries. Your code is vulnerable to sql injection.
  2. Use transactions. It would suck if you deleted all the rows and then somethign happened and the new rows werent inserted. This way you can rollback if the insertions arent completed.


Deleting all rows and inserting new ones is the best method to accomplish what you're trying to accomplish. However, if you want to optimize your code, change your SQL so that you're doing all your inserts in a single query...

INSERT INTO table (col1, col2, col3) VALUES
 (val1, val2, val3),
 (val1, val2, val3),
 (val1, val2, val3),
 (val1, val2, val3),
 (val1, val2, val3)


Deleting rows before updating is good if your new rows count is other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜