# Inserting values using a loop (PHP/MySQL)

**URL:** <https://forum.kirupa.com/t/inserting-values-using-a-loop-php-mysql/79005>\
**Category:** programming\
**Created:** [February 9, 2005, 9:11pm UTC](https://forum.kirupa.com/t/inserting-values-using-a-loop-php-mysql/79005 "2005-02-09T21:11:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Carixpig](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/carixpig/32/304_2.png) [@Carixpig](https://forum.kirupa.com/u/Carixpig)\
**Post date:** [February 9, 2005, 9:11pm UTC](https://forum.kirupa.com/t/inserting-values-using-a-loop-php-mysql/79005/1 "2005-02-09T21:11:01Z")

</div>

Hi Everyone,

I have a php script that uses a loop to insert data into a mysql table. The first page has a list of items followed by text fields that are created from tables values with a ‘while’ loop that increments var $i each time. Text field names are ‘task\_$i’ and ‘hours\_$i’. These I can get to post no problem. The php in the form action goes like so:

```php

$get_tasks = "SELECT task_name FROM chris_tasks;";
$result = mysql_query($get_tasks);
$num_rows = mysql_num_rows($result);

for($i = 0; $i < $num_rows; $i++){
     $task = $HTTP_POST_VARS['task'.$i];
     $task_hours = $HTTP_POST_VARS['hours_'.$i];
     print "Task: $task<br>Hours: $task_hours<br>";//this prints fine for each loop
     $add_tasks = "INSERT INTO $tablename (task_name, task_hours) VALUES ('$task', '$task_hours');";
     print "Query $i: $add_tasks"; //this prints a correct, unique query each time
     $tasks_result = mysql_query($add_tasks); //this line is only successful for the first loop
     if($tasks_result){
          print "Success<br>";
     }else{
          print "Failure<br>";
     }
}

```

With the script as shown (minus spelling errors - I retyped it) it works up until trying to do the $add\_tasks query for a second time (or more). All the data is posted and printed for the first loop and all successive loops, but the query only works once.

I found something similar on Google answers that has the same structure, but it doesn’t seem to work for me.

Can anyone see a problem? I’ve tried adding .$i to the query and the result but then it screws up the posted data (only the first item posts - all others are empty).

Cheers,  
C
