Johan
Johan

Reputation: 35194

Handle javascript array in PHP, inserting multiple rows in to db

Let's say that I send a JS array to a php page using an http post:

var tags = ['foo', 'bar'];

My goal is to do a new INSERT in my db table for each tag (because I suppose I can't insert multiple rows with one query)? How do I loop through the array and insert the values in to the table using mysql_query?

Upvotes: 1

Views: 173

Answers (1)

Amadan
Amadan

Reputation: 198314

Send the post parameters in form tags[]=foo&tags[]=bar. PHP should receive them as a $_REQUEST['tags'] array. Then iterate as normal in PHP.

Alternately, use JSON.stringify(thing) on clientside to get a string representation you can send as a single parameter, then restore it with json_decode(param) on PHP side - and again you get a PHP array.

You can iterate a PHP array using the foreach ($array as $element) { ... } construct.

Also, you can insert multiple rows with one INSERT:

INSERT INTO mytable (col1, col2)
VALUES
  ('foo', 'bar'),
  ('baz', 'moo')

Upvotes: 1

Related Questions