Go through records in database based on submitted form data

I have a table containing products and I have a form which lists all those products with a number input next to each one. The visitor then enters numbers next to each one and submits the form.

I want the Server Connect API script to do all the work. It should receive the form and then look up each product to get a value and add that to a running total.

I’m thinking the easiest way is to put in a Repeat to cycle through the post variables and do a single record query each time to get the value each time. But that seems very poor in terms of server load. So I’m thinking it should be better to load all the data into something like an array and then call on that in the repeat.

Is that the way to go or is there a better method?

You could do:
Set value to $_POST.products.values(‘productid’)

Then
DB query of products where productid IN above value

Then use a where formatter in the repeat to look up the product from the results

1 Like

Thanks Ben. That’s a good option. Can this be achieved within the SC UI or are you having to edit scripts in code view?

All in the UI

Set value, select the POST array and use the values formatter

For the DB query just use the IN condition and point to the set value

In the repeat use set value and point to DB query and apply where condition to filter to the relevant product ID

1 Like

Rather than using the values formatter to give you a flat array for the IN condition, you might have more luck with .flatten('productid')

Ooh, interesting. What does ‘flatten’ do?

Flatten returns a flat array of values from a set of results

if a query step (called query) returned
e.g.

[
{"id":116,"item":"item1"},
{"id":122,"item":"item2"},
{"id":179,"item":"item3"},
{"id":198,"item":"item4"}
]

you could use query.flatten('id')
to get:

[116,122,179,198]
2 Likes

Aah, that’s super helpful. Thanks Ben.

I must confess, arrays are probably my weakest thing. I understand them to a degree but the extra dimension always has me scratching my head. Probably an age thing!

Cheers.

1 Like

Flatten converts a collection property values to an array. Same result as if you use

join(",", "property_name").split(',')
1 Like