Jump to content

Combine foreach loop?


piznac

Recommended Posts

Ok I have these statements:
($rm & $dm are arrays from a form)

[code]foreach($rm as $x) {
  echo $x, '<br>';    
}

foreach($dm as $x) {
  echo $x, '<br>';    
}[/code]

How would I combine these two so I could insert into db. Ive tried everything I can think of,..the best I could come up with was this:

[code]foreach($rm as $x, $dm as $a) {
  insert into my table;    
}[/code]

But of course this does not work,..am I on the right track or way off base?
Link to comment
Share on other sites

Ken,

text data from the form is contained in the arrays. They are generated thru the form. And the db contains 5 text fields. Is this enough info. Maybe I dont know what you are asking

you can find this here
[a href=\"http://rackattackzone.com/test2.php\" target=\"_blank\"]http://rackattackzone.com/test2.php[/a]
Link to comment
Share on other sites

Before you try to add the information into the database, you need to get you code correct and any generated code correct. I looked at the source code from your site and noticed that the HTML for the fields was not correct. You have:
[code]
  <tr>
    <td>1</td>
    <td><input type="text" name="rm[]"
     id="rm[]" size="20" /></td>
    <td><label>
      <input name="dm[]" type="text" id="dm[]" size="20">
    </label>      </td>

    <td><label>
      <input name="store[1]" type="text" id="store[1]" size="8">
    </label></td>
    <td><label>
      <input name="pto[1]" type="text" id="pto[1]" size="10">
    </label></td>
    <td><label>
      <input name="pda[1]" type="text" id="pda[1]" size="10">
    </label></td>

    <td><label>
      <input name="date[1]" type="text" id="date[1]" size="20">
    </label></td>
  </tr>
[/code]
The problems with this code are two fold:[ol type=\'1\'][*]The IDs need to be unique and not arrays, so they should be name something like "dm0", "store0", etc.[*]The Names should be arrays with no indices between the square brackets.[/ol]
Your Javascript to add a row is also incorrect in the area of creating the names and ids.[list][*]For creating the names, you have [code]el2.name = 'dm[]' + iteration;[/code] This would create a name like "dm[]1" which is completely meaningless.[*]You have the same construct for creating the new ids, which will create invalid ids.[/list]Here is the Javascript that creates correct names and ids:
[code]
function addRowToTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);
  
  // left cell
  var cellLeft = row.insertCell(0);
  var textNode = document.createTextNode(iteration);
  cellLeft.appendChild(textNode);
  
    //2nd cell to left
  var cellRight = row.insertCell(1);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'rm[]';
  el.id = 'rm' + iteration;
  el.size = 20;
  
  cellRight.appendChild(el);
  
  // right cell
  var cellRightb = row.insertCell(2);
  var el2 = document.createElement('input');
  el2.type = 'text';
  el2.name = 'dm[]';
  el2.id = 'dm' + iteration;
  el2.size = 20;

  cellRightb.appendChild(el2);
  
  //3rd cell to left
  var cellRightc = row.insertCell(3);
  var el3 = document.createElement('input');
  el3.type = 'text';
  el3.name = 'store[]';
  el3.id = 'store' + iteration;
  el3.size = 8;
  

  cellRightc.appendChild(el3);
  
  //4th cell to left
  var cellRightd = row.insertCell(4);
  var el4 = document.createElement('input');
  el4.type = 'text';
  el4.name = 'pto[]';
  el4.id = 'pto' + iteration;
  el4.size = 10;
  

  cellRightd.appendChild(el4);
  
  //5th cell to left
  var cellRighte = row.insertCell(5);
  var el5 = document.createElement('input');
  el5.type = 'text';
  el5.name = 'pda[]';
  el5.id = 'pda' + iteration;
  el5.size = 10;
  

  cellRighte.appendChild(el5);
  
  //6th cell to left
  var cellRightf = row.insertCell(6);
  var el6 = document.createElement('input');
  el6.type = 'text';
  el6.name = 'date[]';
  el6.id = 'date' + iteration;
  el6.size = 20;
  

  cellRightf.appendChild(el6);
}
[/code]
And here is the code for the form that is also correct:
[code]
<table border="0" id="tblSample">

  <tr>
    <th> </th>
    <th>RM</th>
    <th>DM</th>
    <th>Store</th>
    <th>PTO</th>
    <th>PDA</th>

    <th>Date</th>
  </tr>
  <tr>
    <td>1</td>
    <td><input type="text" name="rm[]"
     id="rm[]" size="20" /></td>
    <td><label>
      <input name="dm[]" type="text" id="dm0" size="20">
    </label>      </td>

    <td><label>
      <input name="store[]" type="text" id="store0" size="8">
    </label></td>
    <td><label>
      <input name="pto[]" type="text" id="pto0" size="10">
    </label></td>
    <td><label>
      <input name="pda[]" type="text" id="pda0" size="10">
    </label></td>

    <td><label>
      <input name="date[]" type="text" id="date0" size="20">
    </label></td>
  </tr>
</table>
[/code]

If you put this code into your test_return.php file, you will see the generated mysql queries:
[code]<?php
$flds = array('rm','dm','store','pto','pda','date');
for($i=0;$i<count($_POST['dm']);$i++) {
    $qtmp = array();
    foreach($flds as $fld)
        if (trim(stripslashes($_POST[$fld][$i])) != '')
            $qtmp[] = $fld . " = '" . mysql_escape_string(trim(stripslashes($_POST[$fld][$i]))) . "'";
    $q = "insert into table set " . implode(', ',$qtmp);
    echo '<pre>' . $q .'</pre>';
}
?>[/code]

In your real script, use the mysql_real_escape_string() function instead of mysql_escape_string().

Ken
Link to comment
Share on other sites


Ken,
Thanks for all your help. But how would I then execute the insert query? I know this is probably simple..but Im so confused.

this is what I have (my connection script is on a seperate page)

[code]<?php
$flds = array('rm','dm','store','pto','pda','date');
for($i=0;$i<count($_POST['dm']);$i++) {
    $qtmp = array();
    foreach($flds as $fld)
        if (trim(stripslashes($_POST[$fld][$i])) != '')
            $qtmp[] = $fld . " = '" . mysql_escape_string(trim(stripslashes($_POST[$fld][$i]))) . "'";
    $q = " INSERT INTO `ptopda` (`rm`, `dm`, `pto`, `pda`, `date`) VALUES (\'rm\', \'dm\', \'store\', \'pto\', \'date\');" . implode(', ',$qtmp);
    echo '<pre>' . $q .'</pre>';
}
?>[/code]

Thanks man.
Link to comment
Share on other sites

Replace [code]<?php $q = " INSERT INTO `ptopda` (`rm`, `dm`, `pto`, `pda`, `date`) VALUES (\'rm\', \'dm\', \'store\', \'pto\', \'date\');" . implode(', ',$qtmp);[/code]
with [code]<?php $q = "insert into ptopda set " . implode(', ',$qtmp); ?>[/code]

The echo statement is just there to show you what got generated. It's not needed in your running code.

You need to put this code into whatever script connects to the database or put your connection code into this script.

The script to do the insert should look something like:
[code]<?php
$flds = array('rm','dm','store','pto','pda','date');
for($i=0;$i<count($_POST['dm']);$i++) {
    $qtmp = array();
    foreach($flds as $fld)
        if (trim(stripslashes($_POST[$fld][$i])) != '')
            $qtmp[] = $fld . " = '" . mysql_escape_string(trim(stripslashes($_POST[$fld][$i]))) . "'";
    $q = "insert into ptopda set " . implode(', ',$qtmp);
    $rs = mysql_query($q) or die ('Problem with the query: ' . $q . '<br>' . mysql_error());
}
?>[/code]

Ken
Link to comment
Share on other sites

I took another look at your javascript code and determined that it can be shorten considerably by using two arrays:
[code]
<script language="JavaScript" type="text/javascript">
// Last updated 2006-02-21
var flds = new Array('','rm','dm','store','pto','pda','date');   // added
var sizes = new Array(0,20,20,8,10,10,20);                      // added
function addRowToTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);
  
  // left cell
  var cellLeft = row.insertCell(0);
  var textNode = document.createTextNode(iteration);
  cellLeft.appendChild(textNode);

  for(i=1;i<flds.length;i++)  { do_add_row(i, row, iteration); }
}

function do_add_row(i, row, iteration) {  // took all of the repetitive code and created this functioin
        var cellRight = row.insertCell(i);
        var el = document.createElement('input');
        el.type = 'text';
        el.name = flds[i] + '[]';
        el.id = flds[i] + iteration;
        el.size = sizes[i];
        cellRight.appendChild(el);
}

function removeRowFromTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
</script>
[/code]

Ken
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.