HKK
HKK

Reputation: 339

$_POST unknown amount of elements

My idea is like an basket on a webshop.

I have a list of items filled into a form by php like:

<?php while($info=msqli_fetch_array($query)){  ?>
    <Input type="text" id="someid1" value="<?php echo $info['info']; ?>"> 
    <Input type="Checkbox" id="checkid1" value="1">
    <Input type="Checkbox" id="checkid2" value="2">
<?php } ?>

I want to use POST for submitting. on the next page for each line should be done this:

MYSQLI query

INSERT into booking (text,variable1,variable2) 
  VALUES ('$_POST['someid1']','$_POST['checkid1']','$_POST['checkid2']'; 

Is there a solution for this?

Upvotes: 0

Views: 149

Answers (3)

Charlie Schliesser
Charlie Schliesser

Reputation: 8237

You can setup named inputs with brackets to get the results as an array server-side. For example:

<input type="text" name="fruits[1]" value="apple" />
<input type="text" name="fruits[2]" value="orange" />

on server side:

<?php
print_r($_POST['fruits']);
?>

array(
  1 => 'apple',
  2 => 'orange',
)

That solves the question. But your code suggests something else that should really be addressed.

You're asking for SQL injection if you just dump $_POST variables into a query. Use PHP's PDO functionality and parameterize your input. Look at the 2nd example in the answer at PHP PDO prepared statements for more info.

Upvotes: 3

jeroen
jeroen

Reputation: 91744

You should use arrays in your html, then you get the corresponding arrays in your $_POST array. Note that you need the name attribute:

<input name="someid[<?php echo $info['id']; ?>]" id="someid1" value="<?php echo $info['info']; ?>">
<input name="checkid[<?php echo $info['id']; ?>]" id="checkid1" value="1">
// etc.

Now $_POST['someid'], etc. will be arrays you can loop over.

Note that you need to use prepared statements to store the information in your database.

Upvotes: -1

Gonz
Gonz

Reputation: 1219

You could use a foreach but IMHO isn't a very secure thing what you want to do.

Upvotes: 0

Related Questions