Can you combine TWO variables in a "while" loop?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Can you combine TWO variables in a "while" loop?

Post by simonmlewis »

Code: Select all

    $counter = 1;
    while ($counter < $calc && $firstname$counter != NULL)
      {
      mysql_query("INSERT INTO diary (userid, entrydate, entrytime, paymenttype, firstname, lastname) VALUES ('0', '$diarydate', '$bookslot', 'ByPhone', '$firstname', '$lastname')");
      $counter = $counter + 1;
      }
This is posting up to 14 rows of fields, but only needs to INSERT the amount of rows used.

So I am passing through the amount of rows available, but want it to only run an INSERT if say 4 have entries in them.

So I am trying to say "do this while counter is below the calcualted figure, and a particular row "firstname1", then "firstname2" have something in them. Trying it with "... && $firstname$counter != NULL, but this fails.

Is there a way to do this??
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: Can you combine TWO variables in a "while" loop?

Post by tr0gd0rr »

I think you need an array. Something like

Code: Select all

$records = array(
    array('firstname'=>'John', 'lastname'=>'Doe'...),
    array('firstname'=>'Jack', 'lastname'=>'Black'...),
);
Then do a foreach:

Code: Select all

foreach($records as $record) {
    // do something with $record['firstname'] and $record['lastname']
}
User avatar
Grizzzzzzzzzz
Forum Contributor
Posts: 125
Joined: Wed Sep 02, 2009 8:51 am

Re: Can you combine TWO variables in a "while" loop?

Post by Grizzzzzzzzzz »

simonmlewis wrote: So I am trying to say "do this while counter is below the calcualted figure, and a particular row "firstname1", then "firstname2" have something in them. Trying it with "... && $firstname$counter != NULL, but this fails.

Is there a way to do this??
surely you mean

Code: Select all

while ($counter < $calc && $firstname[$counter] != NULL)
instead of

Code: Select all

while ($counter < $calc && $firstname$counter != NULL)

but that's assuming $firstname is an array... which it shouldn't be, i'd suggest restructuring your data into a tidyer array format as suggested above
Post Reply