Php foreach in post array

Foreach loop with multiple arrays [duplicate]

I don’t understand how you are sending the data twice. Could you show some sample output if you put an echo in the foreach ?

In truth, no one should be writing code like this anymore. A prepared statement should be defined once and executed as many times as needed.

8 Answers 8

Do you mean something like:

foreach($_POST['something'] as $key => $something) < $example = $_POST['example'][$key]; $query = mysql_query("INSERT INTO table (row, row2) VALUES ('','')"); > 

If $_POSTminimal reproducible example has more values than $_POST[something] then some of the values will be lost

I’m trying to interpret exactly what the OP is asking, based on his comment on sending the data to the database twice. My suspicion is that this is what he means, but is having difficulty explaining

Well, this works, however I get an error: Warning: Invalid argument supplied for foreach() in example.php on line 63 but I used exactly how you wrote.

hey, that was something else, I read wrong line 😀 lol thanks very much this works just how I wanted 😉

SOLUTION FOR MULTIPLE Arrays

Your solution does not seem to send the data twice. Unless if records with the same values appear as a result of issuing your queries. This might mean that you should process your data before constructing your queries.

$sql = array(); foreach($_POST['something'] as $something)< foreach($_POST['example'] as $example)< $sql[] = "INSERT INTO table (row, row2) VALUES ('','')"; > > foreach($sql as $query)

I think the best way would be as a single loop to build a query. This should work even if your arrays are not the same length:

$size1 = count($_POST['something']); $size2 = count($_POST['example']); if( $size1 >= $size2 ) < $size = $size1; >else < $size = $size2; >$sql = "INSERT INTO table (row, row2) VALUES"; $values = array(); for( $i=0; $i $sql .= implode(",", $values); mysql_query($sql); 

Also more secure because it escapes your input. This would also be even easier using placeholders with PDO.

$cnt = count($_POST['something']); $cnt2 = count($_POST['example']); if ($cnt > 0 && $cnt == $cnt2) < $insertArr = array(); for ($i=0; $i$query = "INSERT INTO table (column, column2) VALUES " . implode(", ", $insertArr); mysql_query($query) or trigger_error("Insert failed: " . mysql_error()); > 

Here is another method. This one uses extended inserts, so should be more efficient and quicker, and utilizes mysql_real_escape_string for security reasons. The count check is to just make sure that both fields have the same count, if not then I take this is a mishap. If they are allowed to have a different number of fields, you can simply use the isset() function to check to make sure they contain a value.

This is assuming of course, that you do not want ‘something’ to iterate over all the ‘example’ values and be assigned to each one. If you want that well it is a bit of a change up.

Added an insert array test, if there are no elements no need to update. Thanks Gumbo for that.

Источник

Перебрать массив значений $_POST

Добрый вечер, я пытаюсь написать некий опросник. То есть есть 15 вопросов, которых в будущем будет больше, и напротив каждого вопроса пользователь должен поставить оценку и при желании написать комментарий. Все вопросы для опроса и имена для блоков div подтягиваю с базы. Возможно что имена div-ов тянуть с базы это не совсем правильно, но я это делал для того чтобы идентифицировать их в массиве $_POST, думал так легче будет присвоить комментарий первого вопроса к оценке первого вопроса, второго ко второму и записать все это в базу.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
while($myrow = mysqli_fetch_array($result)){ echo "
".$myrow["department"]."
"; echo "

".$myrow["question"]."

"
; echo "
.$myrow["class_question"]."' required>
"; }

Суть вопроса вот в чем, как мне теперь выловить эти значения на другой странице куда они передаются через $_POST, и присвоить их переменным для того чтобы занести в базу комментарии и оценки которые поставил пользователь? Через foreach

foreach( $_POST as $key => $value){ echo " $key, $value 
"
;

question1, 1
comment1, Комментарий №1
question2, 2
comment2,
question3, 3
comment3,
question4, 4
comment4,
question5, 5
comment5, Комментарий №5
question6, 6
comment6,
question7, 7
comment7,
question8, 8
comment8,
question9, 9
comment9,
question10, 10
comment10, Комментарий №10
question11, 9
comment11,
question12, 8
comment12,
question13, 7
comment13,
question14, 6
comment14,

Запись значений в массив через $_POST
Пожалуйста помогите не могу сделать: С клавиатуры вводятся n чисел. Составьте программу.

Вывод значений из массива $_POST
Имеется форма значения передаются постом. <form action="check.php" style="text-align:center".

Очистить массив $_POST
Доброго времени суток. Подскажите способы полного очищения массива $_POST, unset($_POST) — не.

Как перезаписать массив из $_POST?
Люди добрые подскажите пожалуйста в $_POST лежит многомерный массив, как вывести его в переменную.

WWWPHP, Во-первых нельзя посреди html кода обращаться к базе данных. Вынесете это в область логики формирования данных для вывода. А в html коде используйте foreach. При этому уже используется конструкция с двоеточием, как php играет роль некого шаблонизатора.

Во-вторых вы можете использовать id вопросов из БД. Так же не забудьте прописывать value для всех options

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 $questions = []; while($row = mysqli_fetch_array($result)) { $questions = $row; } ?>  foreach ($questions as $question): ?> div class='block_question'>div class='department'> $question["department"]?>div>; div class='question'>p> $question["question"] ?>p>div> div class='score'> select name="[$question["id"] ?>]answer" required> option value='' hidden=''>0option> option value='1'>1option> option value='2'>2option> option value='3'>3option> option value='4'>4option> option value='5'>5option> option value='6'>6option> option value='7'>7option> option value='8'>8option> option value='9'>9option> option value='10'>10option> select> div> div class='comment_block'>textarea placeholder='Коммментарий' class='comment' name='[$question["id"] ?>]comment' cols='100' rows='4' wrap='virtual' maxlength='100'>textarea>div> div>  endforeach ?>

Добавлено через 2 минуты
И для значений аттрибутов используйте двойные кавычки.

Добавлено через 7 минут
Сорян тупанул.

select name="answer[$question["id"] ?>]" required>

Источник

PHP foreach Loop

The foreach loop — Loops through a block of code for each element in an array.

The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Examples

The following example will output the values of the given array ($colors):

Example

foreach ($colors as $value) echo «$value
«;
>
?>

The following example will output both the keys and the values of the given array ($age):

Example

You will learn more about arrays in the PHP Arrays chapter.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

PHP foreach Loop

The foreach loop — Loops through a block of code for each element in an array.

The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Examples

The following example will output the values of the given array ($colors):

Example

foreach ($colors as $value) echo «$value
«;
>
?>

The following example will output both the keys and the values of the given array ($age):

Example

You will learn more about arrays in the PHP Arrays chapter.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Php система управления версиями
Оцените статью