Re: [PHP] Foreach and mydql_query problem

2013-07-23 Thread Karl-Arne Gjersøyen
It works now and it was a php thing.When I combine a for and while loop
together with Limit in my query it works.
Karl

mandag 22. juli 2013 skrev Liam følgende:

 Shouldn't $_POST['number_of_itemsi'] be $_POST['number_of_items']


 Kind Regards,

 Liam.
 3Sharp Ltd.

 T: 0845 6018370
 F: 0845 6018369

 -Original Message-
 From: Karl-Arne Gjersøyen [mailto:karlar...@gmail.com javascript:;]
 Sent: 22 July 2013 12:39
 To: PHP Mailinglist
 Subject: Re: [PHP] Foreach and mydql_query problem

 2013/7/22 Tamara Temple tamouse.li...@gmail.com javascript:;

 
  On Jul 22, 2013, at 1:19 AM, Karl-Arne Gjersøyen 
  karlar...@gmail.comjavascript:;
 
  wrote:
 
   Hello again.
   I have this this source code that not work as I want...
  
   THe PHP/HTHML form fields is generated by a while loop and looks like
  this:
  
   input type=number name=number_of_items[] size=6 value=?hp
   echo $item; ? required=required
  
  
   the php source code look like this:
   ?php
   if(!empty($_POST['number_of_itemsi'])){
  include('../../connect.php');
  
  foreach($number_of_items as $itemi){
  echo $itemibr;
  
  $sql = UPDATE item_table SET number_item = '$item' WHERE
 date
   = '$todays_date' AND sign = '$username';
  mysql_query($sql,$connect) or die(mysql_error());
   }
   }
  
   ?
  
   The problem is:
   Foreach list every items as expected in PHP doc and I thought that $sql
  and
   mysql_query should be run five times when I have five items.
   But the problem is that only the very last number_of_items is written
  when
   update the form..
   I believe this is becayse number_of_items = '$item in $sqk override
 every
   earlier result.
  
   So my querstion is. How to to update the database in this case?
  
   Thanks again for your good advice  and time to help me.
  
   Karl'
 
  Either the code you posted isn't the actual code, or if it is, the errors
  should be rather obvious. Post *actual* code.
 
 

 // The acutual source code is below:
 // ==
 if(!empty($_POST['antall_kolli'])){
 include('../../tilkobling.php');

 foreach($antall_kolli as $kolli){
 echo $kollibr;

 //echo $kolli. br;
 $sql = UPDATE transportdokument SET antall_kolli_stk =
 '$kolli' WHERE dato = '$dagens_dato' AND signatur = '$brukernavn';
 mysql_query($sql,$tilkobling) or die(mysql_error());
  }
 }

 // THE PHP/HTML Form below:
 include('../../tilkobling.php');

 $sql = SELECT * FROM transportdokument WHERE dato = '$dagens_dato' AND
 signatur = '$brukernavn';
 $resultat = mysql_query($sql, $tilkobling) or die(mysql_error());
 while($rad = mysql_fetch_array($resultat, MYSQL_ASSOC)){
 $valgt_lager = $rad['valgt_lager'];
 $un_nr = $rad['un_nr'];
 $sprengstofftype = $rad['sprengstofftype'];
 $varenavn = $rad['varenavn'];
 $varenr = $rad['varenr'];
 $antall_kolli = $rad['antall_kolli_stk'];
 $adr_vekt_kg = $rad['adr_vekt_kg'];
 $varenavn = $rad['varenavn'];
 $emb = $rad['emb'];
 ?
 tr
 td align=left valign=top?php echo $un_nr; ?/td
 td align=left valign=topstrongSprengstoff/strong,?php echo
 $sprengstofftype; ?/td
 td align=left valign=top?php echo $varenavn; ?/td
 td align=left valign=topstrong1.1D/strong/td
 td align=left valign=topnbsp;/td
 td align=left valign=top?php echo $emb; ?/td
 td align=left valign=top
 input type=hidden name=varenr[] value=?php echo $varenr; ?
 input type=number name=antall_kolli[] size=6 value=?php echo
 $antall_kolli; ? required=required
 /td
 td align=left valign=topinput type=text name=exan_kg_ut[]
 size=6 value=?php echo $adr_vekt_kg; ? required=required/td
 /tr
 ?php
 $total_mengde_kg_adr += $rad['adr_vekt_kg'];
 $total_antall_kolli += $rad['antall_kolli_stk'];
 }

 ?
 include('../../tilkobling.php');

 $sql = SELECT * FROM transportdokument WHERE dato = '$dagens_dato' AND
 signatur = '$brukernavn';
 $resultat = mysql_query($sql, $tilkobling) or die(mysql_error());
 while($rad = mysql_fetch_array($resultat, MYSQL_ASSOC)){
 $valgt_lager = $rad['valgt_lager'];
 $un_nr = $rad['un_nr'];
 $sprengstofftype = $rad['sprengstofftype'];
 $varenavn = $rad['varenavn'];
 $varenr = $rad['varenr'];
 $antall_kolli = $rad['antall_kolli_stk'];
 $adr_vekt_kg = $rad['adr_vekt_kg'];
 $varenavn = $rad['varenavn'];
 $emb = $rad['emb'];
 ?
 tr
 td align=left valign=top?php echo $un_nr; ?/td
 td align=left valign=topstrongSprengstoff/strong,?php echo
 $sprengstofftype; ?/td
 td align=left valign=top?php echo $varenavn; ?/td
 td align=left valign=topstrong1.1D/strong/td
 td align=left valign=topnbsp;/td
 td align=left valign=top?php echo $emb; ?/td
 td align=left valign=top
 input type=hidden name=varenr[] value=?php echo $varenr

Re: [PHP] Foreach and mydql_query problem

2013-07-22 Thread Tamara Temple

On Jul 22, 2013, at 1:19 AM, Karl-Arne Gjersøyen karlar...@gmail.com wrote:

 Hello again.
 I have this this source code that not work as I want...
 
 THe PHP/HTHML form fields is generated by a while loop and looks like this:
 
 input type=number name=number_of_items[] size=6 value=?hp
 echo $item; ? required=required
 
 
 the php source code look like this:
 ?php
 if(!empty($_POST['number_of_itemsi'])){
include('../../connect.php');
 
foreach($number_of_items as $itemi){
echo $itemibr;
 
$sql = UPDATE item_table SET number_item = '$item' WHERE date
 = '$todays_date' AND sign = '$username';
mysql_query($sql,$connect) or die(mysql_error());
 }
 }
 
 ?
 
 The problem is:
 Foreach list every items as expected in PHP doc and I thought that $sql and
 mysql_query should be run five times when I have five items.
 But the problem is that only the very last number_of_items is written when
 update the form..
 I believe this is becayse number_of_items = '$item in $sqk override every
 earlier result.
 
 So my querstion is. How to to update the database in this case?
 
 Thanks again for your good advice  and time to help me.
 
 Karl'

Either the code you posted isn't the actual code, or if it is, the errors 
should be rather obvious. Post *actual* code.


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach and mydql_query problem

2013-07-22 Thread Stuart Dallas

On 22 Jul 2013, at 08:04, Tamara Temple tamouse.li...@gmail.com wrote:

 On Jul 22, 2013, at 1:19 AM, Karl-Arne Gjersøyen karlar...@gmail.com wrote:
 
 Hello again.
 I have this this source code that not work as I want...
 
 THe PHP/HTHML form fields is generated by a while loop and looks like this:
 
 input type=number name=number_of_items[] size=6 value=?hp
 echo $item; ? required=required
 
 
 the php source code look like this:
 ?php
 if(!empty($_POST['number_of_itemsi'])){
   include('../../connect.php');
 
   foreach($number_of_items as $itemi){
   echo $itemibr;
 
   $sql = UPDATE item_table SET number_item = '$item' WHERE date
 = '$todays_date' AND sign = '$username';
   mysql_query($sql,$connect) or die(mysql_error());
}
 }
 
 ?
 
 The problem is:
 Foreach list every items as expected in PHP doc and I thought that $sql and
 mysql_query should be run five times when I have five items.
 But the problem is that only the very last number_of_items is written when
 update the form..
 I believe this is becayse number_of_items = '$item in $sqk override every
 earlier result.
 
 So my querstion is. How to to update the database in this case?
 
 Thanks again for your good advice  and time to help me.
 
 Karl'
 
 Either the code you posted isn't the actual code, or if it is, the errors 
 should be rather obvious. Post *actual* code.

The error is rather obvious: it loops around an array running an update 
statement that will modify a single row in the table, so it's not surprising 
that it appears like only the last entry in the array has been stored.

-Stuart

-- 
Stuart Dallas
3ft9 Ltd
http://3ft9.com/
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach and mydql_query problem

2013-07-22 Thread Karl-Arne Gjersøyen
2013/7/22 Tamara Temple tamouse.li...@gmail.com


 On Jul 22, 2013, at 1:19 AM, Karl-Arne Gjersøyen karlar...@gmail.com
 wrote:

  Hello again.
  I have this this source code that not work as I want...
 
  THe PHP/HTHML form fields is generated by a while loop and looks like
 this:
 
  input type=number name=number_of_items[] size=6 value=?hp
  echo $item; ? required=required
 
 
  the php source code look like this:
  ?php
  if(!empty($_POST['number_of_itemsi'])){
 include('../../connect.php');
 
 foreach($number_of_items as $itemi){
 echo $itemibr;
 
 $sql = UPDATE item_table SET number_item = '$item' WHERE date
  = '$todays_date' AND sign = '$username';
 mysql_query($sql,$connect) or die(mysql_error());
  }
  }
 
  ?
 
  The problem is:
  Foreach list every items as expected in PHP doc and I thought that $sql
 and
  mysql_query should be run five times when I have five items.
  But the problem is that only the very last number_of_items is written
 when
  update the form..
  I believe this is becayse number_of_items = '$item in $sqk override every
  earlier result.
 
  So my querstion is. How to to update the database in this case?
 
  Thanks again for your good advice  and time to help me.
 
  Karl'

 Either the code you posted isn't the actual code, or if it is, the errors
 should be rather obvious. Post *actual* code.



// The acutual source code is below:
// ==
if(!empty($_POST['antall_kolli'])){
include('../../tilkobling.php');

foreach($antall_kolli as $kolli){
echo $kollibr;

//echo $kolli. br;
$sql = UPDATE transportdokument SET antall_kolli_stk =
'$kolli' WHERE dato = '$dagens_dato' AND signatur = '$brukernavn';
mysql_query($sql,$tilkobling) or die(mysql_error());
 }
}

// THE PHP/HTML Form below:
include('../../tilkobling.php');

$sql = SELECT * FROM transportdokument WHERE dato = '$dagens_dato' AND
signatur = '$brukernavn';
$resultat = mysql_query($sql, $tilkobling) or die(mysql_error());
while($rad = mysql_fetch_array($resultat, MYSQL_ASSOC)){
$valgt_lager = $rad['valgt_lager'];
$un_nr = $rad['un_nr'];
$sprengstofftype = $rad['sprengstofftype'];
$varenavn = $rad['varenavn'];
$varenr = $rad['varenr'];
$antall_kolli = $rad['antall_kolli_stk'];
$adr_vekt_kg = $rad['adr_vekt_kg'];
$varenavn = $rad['varenavn'];
$emb = $rad['emb'];
?
tr
td align=left valign=top?php echo $un_nr; ?/td
td align=left valign=topstrongSprengstoff/strong,?php echo
$sprengstofftype; ?/td
td align=left valign=top?php echo $varenavn; ?/td
td align=left valign=topstrong1.1D/strong/td
td align=left valign=topnbsp;/td
td align=left valign=top?php echo $emb; ?/td
td align=left valign=top
input type=hidden name=varenr[] value=?php echo $varenr; ?
input type=number name=antall_kolli[] size=6 value=?php echo
$antall_kolli; ? required=required
/td
td align=left valign=topinput type=text name=exan_kg_ut[]
size=6 value=?php echo $adr_vekt_kg; ? required=required/td
/tr
?php
$total_mengde_kg_adr += $rad['adr_vekt_kg'];
$total_antall_kolli += $rad['antall_kolli_stk'];
}

?
include('../../tilkobling.php');

$sql = SELECT * FROM transportdokument WHERE dato = '$dagens_dato' AND
signatur = '$brukernavn';
$resultat = mysql_query($sql, $tilkobling) or die(mysql_error());
while($rad = mysql_fetch_array($resultat, MYSQL_ASSOC)){
$valgt_lager = $rad['valgt_lager'];
$un_nr = $rad['un_nr'];
$sprengstofftype = $rad['sprengstofftype'];
$varenavn = $rad['varenavn'];
$varenr = $rad['varenr'];
$antall_kolli = $rad['antall_kolli_stk'];
$adr_vekt_kg = $rad['adr_vekt_kg'];
$varenavn = $rad['varenavn'];
$emb = $rad['emb'];
?
tr
td align=left valign=top?php echo $un_nr; ?/td
td align=left valign=topstrongSprengstoff/strong,?php echo
$sprengstofftype; ?/td
td align=left valign=top?php echo $varenavn; ?/td
td align=left valign=topstrong1.1D/strong/td
td align=left valign=topnbsp;/td
td align=left valign=top?php echo $emb; ?/td
td align=left valign=top
input type=hidden name=varenr[] value=?php echo $varenr; ?
input type=number name=antall_kolli[] size=6 value=?php echo
$antall_kolli; ? required=required
/td
td align=left valign=topinput type=text name=exan_kg_ut[]
size=6 value=?php echo $adr_vekt_kg; ? required=required/td
/tr
?php
$total_mengde_kg_adr += $rad['adr_vekt_kg'];
$total_antall_kolli += $rad['antall_kolli_stk'];
}

?


Re: [PHP] Foreach and mydql_query problem

2013-07-22 Thread Karl-Arne Gjersøyen
2013/7/22 Stuart Dallas stu...@3ft9.com


 On 22 Jul 2013, at 08:04, Tamara Temple tamouse.li...@gmail.com wrote:

  On Jul 22, 2013, at 1:19 AM, Karl-Arne Gjersøyen karlar...@gmail.com
 wrote:
 
  Hello again.
  I have this this source code that not work as I want...
 
  THe PHP/HTHML form fields is generated by a while loop and looks like
 this:
 
  input type=number name=number_of_items[] size=6 value=?hp
  echo $item; ? required=required
 
 
  the php source code look like this:
  ?php
  if(!empty($_POST['number_of_itemsi'])){
include('../../connect.php');
 
foreach($number_of_items as $itemi){
echo $itemibr;
 
$sql = UPDATE item_table SET number_item = '$item' WHERE date
  = '$todays_date' AND sign = '$username';
mysql_query($sql,$connect) or die(mysql_error());
 }
  }
 
  ?
 
  The problem is:
  Foreach list every items as expected in PHP doc and I thought that $sql
 and
  mysql_query should be run five times when I have five items.
  But the problem is that only the very last number_of_items is written
 when
  update the form..
  I believe this is becayse number_of_items = '$item in $sqk override
 every
  earlier result.
 
  So my querstion is. How to to update the database in this case?
 
  Thanks again for your good advice  and time to help me.
 
  Karl'
 
  Either the code you posted isn't the actual code, or if it is, the
 errors should be rather obvious. Post *actual* code.

 The error is rather obvious: it loops around an array running an update
 statement that will modify a single row in the table, so it's not
 surprising that it appears like only the last entry in the array has been
 stored.

 Yes, i know that only one a singe row is updated and that is the problem.
What can I do to update several rows at the same time?
Thank you very much for all your good adivce.

Karl


Re: [PHP] Foreach and mydql_query problem

2013-07-22 Thread Stuart Dallas
On 22 Jul 2013, at 12:56, Karl-Arne Gjersøyen karlar...@gmail.com wrote:

 2013/7/22 Stuart Dallas stu...@3ft9.com
 
 
 On 22 Jul 2013, at 08:04, Tamara Temple tamouse.li...@gmail.com wrote:
 
 On Jul 22, 2013, at 1:19 AM, Karl-Arne Gjersøyen karlar...@gmail.com
 wrote:
 
 Hello again.
 I have this this source code that not work as I want...
 
 THe PHP/HTHML form fields is generated by a while loop and looks like
 this:
 
 input type=number name=number_of_items[] size=6 value=?hp
 echo $item; ? required=required
 
 
 the php source code look like this:
 ?php
 if(!empty($_POST['number_of_itemsi'])){
  include('../../connect.php');
 
  foreach($number_of_items as $itemi){
  echo $itemibr;
 
  $sql = UPDATE item_table SET number_item = '$item' WHERE date
 = '$todays_date' AND sign = '$username';
  mysql_query($sql,$connect) or die(mysql_error());
   }
 }
 
 ?
 
 The problem is:
 Foreach list every items as expected in PHP doc and I thought that $sql
 and
 mysql_query should be run five times when I have five items.
 But the problem is that only the very last number_of_items is written
 when
 update the form..
 I believe this is becayse number_of_items = '$item in $sqk override
 every
 earlier result.
 
 So my querstion is. How to to update the database in this case?
 
 Thanks again for your good advice  and time to help me.
 
 Karl'
 
 Either the code you posted isn't the actual code, or if it is, the
 errors should be rather obvious. Post *actual* code.
 
 The error is rather obvious: it loops around an array running an update
 statement that will modify a single row in the table, so it's not
 surprising that it appears like only the last entry in the array has been
 stored.
 
 Yes, i know that only one a singe row is updated and that is the problem.
 What can I do to update several rows at the same time?
 Thank you very much for all your good advice.

Are you sure you want to update several rows, or do you actually want to insert 
several rows?

This is pretty basic database stuff, and is off-topic for this list.

-Stuart

-- 
Stuart Dallas
3ft9 Ltd
http://3ft9.com/
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach and mydql_query problem

2013-07-22 Thread Karl-Arne Gjersøyen
2013/7/22 Stuart Dallas stu...@3ft9.com

 On 22 Jul 2013, at 12:56, Karl-Arne Gjersøyen karlar...@gmail.com wrote:

  2013/7/22 Stuart Dallas stu...@3ft9.com
 
 
  On 22 Jul 2013, at 08:04, Tamara Temple tamouse.li...@gmail.com
 wrote:
 
  On Jul 22, 2013, at 1:19 AM, Karl-Arne Gjersøyen karlar...@gmail.com
  wrote:
 
  Hello again.
  I have this this source code that not work as I want...
 
  THe PHP/HTHML form fields is generated by a while loop and looks like
  this:
 
  input type=number name=number_of_items[] size=6 value=?hp
  echo $item; ? required=required
 
 
  the php source code look like this:
  ?php
  if(!empty($_POST['number_of_itemsi'])){
   include('../../connect.php');
 
   foreach($number_of_items as $itemi){
   echo $itemibr;
 
   $sql = UPDATE item_table SET number_item = '$item' WHERE
 date
  = '$todays_date' AND sign = '$username';
   mysql_query($sql,$connect) or die(mysql_error());
}
  }
 
  ?
 
  The problem is:
  Foreach list every items as expected in PHP doc and I thought that
 $sql
  and
  mysql_query should be run five times when I have five items.
  But the problem is that only the very last number_of_items is written
  when
  update the form..
  I believe this is becayse number_of_items = '$item in $sqk override
  every
  earlier result.
 
  So my querstion is. How to to update the database in this case?
 
  Thanks again for your good advice  and time to help me.
 
  Karl'
 
  Either the code you posted isn't the actual code, or if it is, the
  errors should be rather obvious. Post *actual* code.
 
  The error is rather obvious: it loops around an array running an update
  statement that will modify a single row in the table, so it's not
  surprising that it appears like only the last entry in the array has
 been
  stored.
 
  Yes, i know that only one a singe row is updated and that is the
 problem.
  What can I do to update several rows at the same time?
  Thank you very much for all your good advice.

 Are you sure you want to update several rows, or do you actually want to
 insert several rows?

 This is pretty basic database stuff, and is off-topic for this list.



OK. Sorry. I thought it was a PHP question for a way to update several
mysql rows by PHP code.

Karl


Re: [PHP] Foreach and mydql_query problem

2013-07-22 Thread Stuart Dallas
On 22 Jul 2013, at 13:25, Karl-Arne Gjersøyen karlar...@gmail.com wrote:

 2013/7/22 Stuart Dallas stu...@3ft9.com
 On 22 Jul 2013, at 12:56, Karl-Arne Gjersøyen karlar...@gmail.com wrote:
 
  2013/7/22 Stuart Dallas stu...@3ft9.com
 
 
  On 22 Jul 2013, at 08:04, Tamara Temple tamouse.li...@gmail.com wrote:
 
  On Jul 22, 2013, at 1:19 AM, Karl-Arne Gjersøyen karlar...@gmail.com
  wrote:
 
  Hello again.
  I have this this source code that not work as I want...
 
  THe PHP/HTHML form fields is generated by a while loop and looks like
  this:
 
  input type=number name=number_of_items[] size=6 value=?hp
  echo $item; ? required=required
 
 
  the php source code look like this:
  ?php
  if(!empty($_POST['number_of_itemsi'])){
   include('../../connect.php');
 
   foreach($number_of_items as $itemi){
   echo $itemibr;
 
   $sql = UPDATE item_table SET number_item = '$item' WHERE date
  = '$todays_date' AND sign = '$username';
   mysql_query($sql,$connect) or die(mysql_error());
}
  }
 
  ?
 
  The problem is:
  Foreach list every items as expected in PHP doc and I thought that $sql
  and
  mysql_query should be run five times when I have five items.
  But the problem is that only the very last number_of_items is written
  when
  update the form..
  I believe this is becayse number_of_items = '$item in $sqk override
  every
  earlier result.
 
  So my querstion is. How to to update the database in this case?
 
  Thanks again for your good advice  and time to help me.
 
  Karl'
 
  Either the code you posted isn't the actual code, or if it is, the
  errors should be rather obvious. Post *actual* code.
 
  The error is rather obvious: it loops around an array running an update
  statement that will modify a single row in the table, so it's not
  surprising that it appears like only the last entry in the array has been
  stored.
 
  Yes, i know that only one a singe row is updated and that is the problem.
  What can I do to update several rows at the same time?
  Thank you very much for all your good advice.
 
 Are you sure you want to update several rows, or do you actually want to 
 insert several rows?
 
 This is pretty basic database stuff, and is off-topic for this list.
  
 
 OK. Sorry. I thought it was a PHP question for a way to update several mysql 
 rows by PHP code.

If you want to UPDATE several rows then you must have unique identifiers for 
those rows. If you don't then I'm guessing what you actually want to do is 
INSERT those rows.

It's off-topic in the same way as asking a mechanic how to fit a bunch of stuff 
in your car. It's the MySQL part that you're having a problem with, not the 
PHP. I strongly recommend that you use the MySQL command line to run the 
queries you think you need to run, checking what the table looks like after 
each one. Once you know what queries you need to run you will more effectively 
be able to write the PHP wrapper around those queries.

-Stuart

-- 
Stuart Dallas
3ft9 Ltd
http://3ft9.com/
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach and mydql_query problem

2013-07-22 Thread Jim Giner
Your original code snippet had some errors.  It really couldn't have 
been what you wanted to do.


Example:

You have a named field of 'number_of_items' and then you try to retreive 
$_POST['number_of_itemsi'].  That won't work.


Then you have a var called $number_of_items which we don't see defined, 
and you are assigning each to $itemi but then you use $item in your 
query.  Very Confusing!!


Perhaps if you clean up the errors you might see better results.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach and mydql_query problem

2013-07-22 Thread Jim Lucas

On 07/22/2013 04:39 AM, Karl-Arne Gjersøyen wrote:




Might I suggest that you place your include for ../../tilkobling.php at 
the very top of this page?  It would save you from possibly including it 
twice.



// The acutual source code is below:
// ==
if(!empty($_POST['antall_kolli'])){
 include('../../tilkobling.php');   ---  remove this line

 foreach($antall_kolli as $kolli){
 echo $kollibr;

 //echo $kolli. br;
 $sql = UPDATE transportdokument SET antall_kolli_stk =
'$kolli' WHERE dato = '$dagens_dato' AND signatur = '$brukernavn';
 mysql_query($sql,$tilkobling) or die(mysql_error());
  }


Your WHERE conditions are the same, that is why it is updating a single 
row.  Where are $dagens_dato and $brukernavn being defined?  As others 
have stated, you need to include a unique identifier in your query so 
your query updates a specific record.



}

// THE PHP/HTML Form below:
include('../../tilkobling.php');   ---  move this to the top of the 
script

 $sql = SELECT * FROM transportdokument WHERE dato = '$dagens_dato' AND
signatur = '$brukernavn';
 $resultat = mysql_query($sql, $tilkobling) or die(mysql_error());
 while($rad = mysql_fetch_array($resultat, MYSQL_ASSOC)){
 $valgt_lager = $rad['valgt_lager'];
 $un_nr = $rad['un_nr'];
 $sprengstofftype = $rad['sprengstofftype'];
 $varenavn = $rad['varenavn'];
 $varenr = $rad['varenr'];
 $antall_kolli = $rad['antall_kolli_stk'];
 $adr_vekt_kg = $rad['adr_vekt_kg'];
 $varenavn = $rad['varenavn'];
 $emb = $rad['emb'];
?
tr
 td align=left valign=top?php echo $un_nr; ?/td
 td align=left valign=topstrongSprengstoff/strong,?php echo
$sprengstofftype; ?/td
 td align=left valign=top?php echo $varenavn; ?/td
 td align=left valign=topstrong1.1D/strong/td
 td align=left valign=topnbsp;/td
 td align=left valign=top?php echo $emb; ?/td
 td align=left valign=top
 input type=hidden name=varenr[] value=?php echo $varenr; ?
 input type=number name=antall_kolli[] size=6 value=?php echo
$antall_kolli; ? required=required
 /td
 td align=left valign=topinput type=text name=exan_kg_ut[]
size=6 value=?php echo $adr_vekt_kg; ? required=required/td
/tr
?php
$total_mengde_kg_adr += $rad['adr_vekt_kg'];
$total_antall_kolli += $rad['antall_kolli_stk'];
 }

?



--
Jim Lucas

http://www.cmsws.com/
http://www.cmsws.com/examples/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach

2012-10-17 Thread Matijn Woudt
On Wed, Oct 17, 2012 at 1:25 AM, Larry Garfield la...@garfieldtech.com wrote:

 For the love of god, please stop using ext/mysql (aka the mysql_*
 functions).  It's insecure and slow and lacks features.

 Instead, use PDO, and bind your parameters.  As a nice bonus, the result
 from a PDO-based query is not a raw resource but an iteratable object, which
 means you can foreach() it.

 http://php.net/manual/en/book.pdo.php

 $conn = new PDO(...);
 $result = $conn-query(SELECT * FROM items);
 foreach ($result as $record) {
   // Do something with each record here.
 }

 --Larry Garfield


Yes, the mysql extension is deprecated, but what's wrong with mysqli?
mysqli has the advantage that you don't need to keep a database handle
floating around, but you can just use mysqli_query everywhere.
When having multiple files and classes, it's terrible to pass $db to
each function/class, and I hate to use the global keyword.

just use while($record = $result-fetch_array()) instead of
foreach($result as $record)

And you mention ext/mysql is slow, well don't know about that, but PDO
is a bit slower than mysqli atleast.
I quote from [1]:
For inserts, there was no significant difference between MySQLi and
PDO (prepared statements or not). For selects, MySQLi was about 2.5%
faster for non-prepared statements and about 6.7% faster for prepared
statements. 

- Matijn

[1] http://jnrbsn.com/2010/06/mysqli-vs-pdo-benchmarks

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach

2012-10-17 Thread Larry Garfield

On 10/17/12 10:17 AM, Matijn Woudt wrote:

On Wed, Oct 17, 2012 at 1:25 AM, Larry Garfield la...@garfieldtech.com wrote:


For the love of god, please stop using ext/mysql (aka the mysql_*
functions).  It's insecure and slow and lacks features.

Instead, use PDO, and bind your parameters.  As a nice bonus, the result
from a PDO-based query is not a raw resource but an iteratable object, which
means you can foreach() it.

http://php.net/manual/en/book.pdo.php

$conn = new PDO(...);
$result = $conn-query(SELECT * FROM items);
foreach ($result as $record) {
   // Do something with each record here.
}

--Larry Garfield



Yes, the mysql extension is deprecated, but what's wrong with mysqli?
mysqli has the advantage that you don't need to keep a database handle
floating around, but you can just use mysqli_query everywhere.
When having multiple files and classes, it's terrible to pass $db to
each function/class, and I hate to use the global keyword.

just use while($record = $result-fetch_array()) instead of
foreach($result as $record)

And you mention ext/mysql is slow, well don't know about that, but PDO
is a bit slower than mysqli atleast.
I quote from [1]:
For inserts, there was no significant difference between MySQLi and
PDO (prepared statements or not). For selects, MySQLi was about 2.5%
faster for non-prepared statements and about 6.7% faster for prepared
statements. 

- Matijn

[1] http://jnrbsn.com/2010/06/mysqli-vs-pdo-benchmarks


Nothing is wrong with mysqli per se.  It's up to date and secure, and 
certainly better than ext/mysql.  I recommend PDO over mysqli because:


1) PHP-engine-level global state (ie, not specifying a connection) is 
the source of most (although not quite all) evil.  Really, that way lies 
pain once you get into anything reasonably complicated and want to be 
able to test it properly.


2) PDO is installed by default on virtually every PHP system in the 
world.  ext/mysqli has never been part of the default build of PHP, and 
many to most web hosts don't have it installed.


3) mysqli's API is a bizarre hybrid of procedural and OO that confuses 
the heck out of me.  PDO's is far from perfect, but is more consistent 
and cleanly OO from the get-go.


I skipped mysqli entirely and went straight to PDO when it became available.

--Larry Garfield

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach

2012-10-17 Thread tamouse mailing lists
On Wed, Oct 17, 2012 at 6:07 PM, Larry Garfield la...@garfieldtech.com wrote:
 Nothing is wrong with mysqli per se.  It's up to date and secure, and
 certainly better than ext/mysql.  I recommend PDO over mysqli because:

 1) PHP-engine-level global state (ie, not specifying a connection) is the
 source of most (although not quite all) evil.  Really, that way lies pain
 once you get into anything reasonably complicated and want to be able to
 test it properly.

I don't have a clue what you are saying here.

 2) PDO is installed by default on virtually every PHP system in the world.
 ext/mysqli has never been part of the default build of PHP, and many to most
 web hosts don't have it installed.

Do you have any reasonable data on this? Where do you get this notion
that it's not installed on many to most web hosts? Every distro I've
encountered has it built in to the version installed (ubuntu, debian,
centos, fedora, os/x, gentoo, funtoo, and many i've forgotten).

You are correct that you must specify --with-mysqli in the configure
command if you build php from source.

 3) mysqli's API is a bizarre hybrid of procedural and OO that confuses the
 heck out of me.  PDO's is far from perfect, but is more consistent and
 cleanly OO from the get-go.

Err...ah...err -- mysqli is not a hybrid. It offers both OO and
procedural, but you only use one or the other. If you mix them
together in the same script/app, you could be looking for a lot of
trouble.

 I skipped mysqli entirely and went straight to PDO when it became available.

This might be the source of your bias.

That said, I use PDO now all the time.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] foreach

2012-10-16 Thread Steven Staples
 Here's what I ended up with after you gave me the advise:
 $result = mysql_query(SELECT * FROM items);
   $rows = array();
   while($row = mysql_fetch_array($result))
$rows[] = $row;
   foreach($rows as $row){
   $product = $row['product'];
   $price = $row['price'];
 echo $product ;
 echo $price ;
 
 
 $justright = 0;
 $toohigh = 5; //I was going to use this to check if the price was too
 high
   just so I could use an elseif in the
exercise, but
 I realized that
   it would only work if the if() evaluated to
false,
 which would be
   impossible. Ahhh pizz on it, it was fun
anyway! :-
 )
 
 if($justright = $price){
  echo Not bad. I'll buy it.br /;
   } else
  echo Too expensive I'm going home LOL ;
 
   }
 
 It's a dumb script that makes no sense but I had a blast doing this. When
 things start coming together like this, it gets so gratifying. :-)
 
  --
 David M.


David, 

Just putting this out there, but the use of a foreach() loop here, is
redundant...
You are putting your query results into an array, and then looping through
them after with the foreach(), instead of just using the while loop to loop
through them initially... so you're doing the same thing, twice, just using
the foreach() after the while.

One thing I was always told when I was learning c++ (my teacher was anal,
and always forced us to try and be more efficient), using = uses more cpu
cycles, than  or , so when you're checking 0 = 0.1 true, false, you could
exchange your check to be 0  0.1 false, else true...

Also, setting the variable $product and $price, with the value from the
database $row['product'], would be less cycles than to just echo the
$row['product']...

That is just some $0.02...  I wouldn't personally create more code, just to
try something out... use the right function for the job, write less code
than needed (sometimes, a little more code for readability is better
though), and most importantly... have fun.

One thing I do, is my coding and bracing style is something that Tedd
Sperling doesn't like (there have been many discussions about bracing
styles),  I keep my braces all in line, and always use them in my if()s...
ie:
If($yourmom == $hot)
{
Echo MILF!;
}
Else
{
Echo Pass.;
}

And I do this for readability, so I can see if I forgot a brace somewhere,
and also, I always know that there are braces (with a 4space indentation, or
tab stops set at 4 space)

1 more point, doing multiline comments, use /*  insert comment here */  and
not just //, and with that, I use inline comments with #,  but that is just
me.

Overall though, I am glad to see you're learning, and having fun doing so...


Steve Staples.


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach

2012-10-16 Thread Matijn Woudt
On Tue, Oct 16, 2012 at 3:46 PM, Steven Staples sstap...@mnsi.net wrote:
 One thing I do, is my coding and bracing style is something that Tedd
 Sperling doesn't like (there have been many discussions about bracing
 styles),  I keep my braces all in line, and always use them in my if()s...
 ie:
snip violent language

 And I do this for readability, so I can see if I forgot a brace somewhere,
 and also, I always know that there are braces (with a 4space indentation, or
 tab stops set at 4 space)


 Steve Staples.


Steve,

Please watch your language on this list.

- Matijn

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] foreach

2012-10-16 Thread Steven Staples
 -Original Message-
 From: Matijn Woudt [mailto:tijn...@gmail.com]
 Steve,
 
 Please watch your language on this list.
 
 - Matijn
 

My apologies, I guess using $foo == $bar would have been a better choice... I 
forget sometimes, I am used to chatting with my close friends, where stuff like 
that is pretty tame.

I meant no disrespect to anyone.

Steve Staples.


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] foreach

2012-10-16 Thread Ashley Sheridan
On Tue, 2012-10-16 at 10:11 -0400, Steven Staples wrote:

  -Original Message-
  From: Matijn Woudt [mailto:tijn...@gmail.com]
  Steve,
  
  Please watch your language on this list.
  
  - Matijn
  
 
 My apologies, I guess using $foo == $bar would have been a better choice... I 
 forget sometimes, I am used to chatting with my close friends, where stuff 
 like that is pretty tame.
 
 I meant no disrespect to anyone.
 
 Steve Staples.
 
 


I wouldn't have said the language was violent, maybe just a tad too
'Friday', but hey.

I also prefer my braces lined up like that. Sure it results in a few
more lines, but it sure makes more sense when I'm going over old code.

-- 
Thanks,
Ash
http://www.ashleysheridan.co.uk




Re: [PHP] foreach

2012-10-16 Thread Jim Giner

On 10/15/2012 8:39 PM, Jim Lucas wrote:

On 10/15/2012 05:16 PM, David McGlone wrote:

I've been sitting here playing around with foreach() and I'm wondering
why I
am getting these results. here's what I've been fooling around with.
the code
has no perticular meaning, but I noticed if the script fails, I get the
sentence Too expensive I'm going home LOL 6 times because there are
6 words
in the sentence. I also have a database that looks like this:

product_idproductprice
1Milk2.59
2bread1.05

And when $row is equal to 0 the output I get is
1 1 Milk Milk 2.59 2.59 Which is printed to the screen according to
how many
rows are in the db I belive.

So my question is why this behavior? I was expecting something like a
while
loop.



Code please.


You want code?  IF it's anything like what he showed already, who cares?

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach

2012-10-16 Thread David McGlone
On Tuesday, October 16, 2012 09:46:26 AM you wrote:
  Here's what I ended up with after you gave me the advise:
  $result = mysql_query(SELECT * FROM items);
  
$rows = array();
while($row = mysql_fetch_array($result))

 $rows[] = $row;

foreach($rows as $row){
$product = $row['product'];
$price = $row['price'];

  echo $product ;
  echo $price ;
  
  
  $justright = 0;
  $toohigh = 5; //I was going to use this to check if the price was too
  
  high
  
  just so I could use an elseif in the
 
 exercise, but
 
  I realized that
  
  it would only work if the if() evaluated to
 
 false,
 
  which would be
  
  impossible. Ahhh pizz on it, it was fun
 
 anyway! :-
 
  )
  
  if($justright = $price){
  
   echo Not bad. I'll buy it.br /;
   
} else
   
   echo Too expensive I'm going home LOL ;

}
  
  It's a dumb script that makes no sense but I had a blast doing this. When
  things start coming together like this, it gets so gratifying. :-)
  
   --
  
  David M.
 
 David,
 
 Just putting this out there, but the use of a foreach() loop here, is
 redundant...
 You are putting your query results into an array, and then looping through
 them after with the foreach(), instead of just using the while loop to loop
 through them initially... so you're doing the same thing, twice, just using
 the foreach() after the while.
 
 One thing I was always told when I was learning c++ (my teacher was anal,
 and always forced us to try and be more efficient), using = uses more cpu
 cycles, than  or , so when you're checking 0 = 0.1 true, false, you could
 exchange your check to be 0  0.1 false, else true...

This is what I like to hear. It's stuff like this this that I haven't found in 
a text book. Even when Bastian said $row is a pointer. Ah Yes! That 
helped tremendously.

 
 Also, setting the variable $product and $price, with the value from the
 database $row['product'], would be less cycles than to just echo the
 $row['product']...

Hehehehe who said I wanted this exercise to be easy? LMBO
 
 That is just some $0.02...  I wouldn't personally create more code, just to
 try something out... use the right function for the job, write less code
 than needed (sometimes, a little more code for readability is better
 though), and most importantly... have fun.

I appreciate your feedback and it's conversations like this that help the 
most.
 
 One thing I do, is my coding and bracing style is something that Tedd
 Sperling doesn't like (there have been many discussions about bracing
 styles),  I keep my braces all in line, and always use them in my if()s...
 ie:
   If($yourmom == $hot)
   {
   Echo MILF!;
   }
   Else
   {
   Echo Pass.;
   }
 
 And I do this for readability, so I can see if I forgot a brace somewhere,
 and also, I always know that there are braces (with a 4space indentation, or
 tab stops set at 4 space)

I have Kate set up to create auto brackets so I'll never forget to close one 
and I have lines on the left hand side that connect each open bracket to it's 
corresponding close bracket. Any open end lines means I'm missing something.
 
 1 more point, doing multiline comments, use /*  insert comment here */  and
 not just //, and with that, I use inline comments with #,  but that is just
 me.

That long comment I made about the variable I didn't use was actually typed in 
the e-mail in my reply to Bastian and wasn't in the code. If it was in the 
code I would have used /* */
 
 Overall though, I am glad to see you're learning, and having fun doing so...

Thanks. The whole purpose of me doing this was to get to play with foreach() 
and I've been down with while for a while.. LMBO it was just too easy to use 
while and I was trying to force myself to keep thinking.

When Bastian pointed out that $row was a pointer, just that little bit of info 
changed the whole course of how I was thinking. I was thinking $row was an 
array with all the results in it and with his little bit of info and knowing I 
wanted to play around with foreach() I just stuck to whatever came up and this 
is what the result was... :-)

Alot of times I need to be reminded. Like hey! that's a CONSTANT not a 
$variable!!

-- 
David M.



Re: [PHP] foreach

2012-10-16 Thread Larry Garfield

On 10/15/12 9:05 PM, David McGlone wrote:

On Monday, October 15, 2012 08:21:23 PM you wrote:

Bastien Koert

On 2012-10-15, at 8:16 PM, David McGlone da...@dmcentral.net wrote:

I've been sitting here playing around with foreach() and I'm wondering why
I am getting these results. here's what I've been fooling around with.
the code has no perticular meaning, but I noticed if the script fails, I
get the sentence Too expensive I'm going home LOL 6 times because there
are 6 words in the sentence. I also have a database that looks like this:

product_idproductprice
1Milk2.59
2bread1.05

And when $row is equal to 0 the output I get is
1 1 Milk Milk 2.59 2.59 Which is printed to the screen according to how
many rows are in the db I belive.

So my question is why this behavior? I was expecting something like a
while
loop.


Dave,

Foreach is an iterator over an array. Your $row is a pointer to a db result
set. If you were to pass the $row result set to the foreach as an array,
you'd get what you think you should

Www.php.net/foreach


Thanks Bastien.
Heres what I started with:

$result = mysql_query(SELECT * FROM items);
$row = mysql_fetch_array($result);
foreach($row as $rows){
$row = 0;
if($row == 0){
echo $rows;
} else{
echo Too expensive I'm going home LOL;
}
}

Here's what I ended up with after you gave me the advise:
$result = mysql_query(SELECT * FROM items);
   $rows = array();
   while($row = mysql_fetch_array($result))
$rows[] = $row;
   foreach($rows as $row){
   $product = $row['product'];
   $price = $row['price'];
 echo $product ;
 echo $price ;


 $justright = 0;
 $toohigh = 5; //I was going to use this to check if the price was too high
just so I could use an elseif in the exercise, 
but I realized that
it would only work if the if() evaluated to 
false, which would be   
impossible. Ahhh pizz on it, it was fun anyway! 
:-)

 if($justright = $price){
  echo Not bad. I'll buy it.br /;
   } else
  echo Too expensive I'm going home LOL ;

   }


For the love of god, please stop using ext/mysql (aka the mysql_* 
functions).  It's insecure and slow and lacks features.


Instead, use PDO, and bind your parameters.  As a nice bonus, the result 
from a PDO-based query is not a raw resource but an iteratable object, 
which means you can foreach() it.


http://php.net/manual/en/book.pdo.php

$conn = new PDO(...);
$result = $conn-query(SELECT * FROM items);
foreach ($result as $record) {
  // Do something with each record here.
}

--Larry Garfield

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach

2012-10-16 Thread tamouse mailing lists
On Tue, Oct 16, 2012 at 6:25 PM, Larry Garfield la...@garfieldtech.com wrote:
 Instead, use PDO, and bind your parameters.  As a nice bonus, the result
 from a PDO-based query is not a raw resource but an iteratable object, which
 means you can foreach() it.

 http://php.net/manual/en/book.pdo.php

 $conn = new PDO(...);
 $result = $conn-query(SELECT * FROM items);
 foreach ($result as $record) {
   // Do something with each record here.
 }

 --Larry Garfield

Bonus round:

Remember if you do multiple queries to also issue the close when you
are done with the current result set:

$result-closeCursor();

(not all dbms drivers have this limitation, but defensive coding is defensive.)

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach

2012-10-15 Thread Bastien


Bastien Koert

On 2012-10-15, at 8:16 PM, David McGlone da...@dmcentral.net wrote:

 I've been sitting here playing around with foreach() and I'm wondering why I 
 am getting these results. here's what I've been fooling around with. the code 
 has no perticular meaning, but I noticed if the script fails, I get the 
 sentence Too expensive I'm going home LOL 6 times because there are 6 words 
 in the sentence. I also have a database that looks like this:
 
 product_idproductprice
 1Milk2.59
 2bread1.05
 
 And when $row is equal to 0 the output I get is
 1 1 Milk Milk 2.59 2.59 Which is printed to the screen according to how many 
 rows are in the db I belive.
 
 So my question is why this behavior? I was expecting something like a while 
 loop.
 
 -- 
 David M.
 

Dave,

Foreach is an iterator over an array. Your $row is a pointer to a db result 
set. If you were to pass the $row result set to the foreach as an array, you'd 
get what you think you should

Www.php.net/foreach
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach

2012-10-15 Thread Jim Lucas

On 10/15/2012 05:16 PM, David McGlone wrote:

I've been sitting here playing around with foreach() and I'm wondering why I
am getting these results. here's what I've been fooling around with. the code
has no perticular meaning, but I noticed if the script fails, I get the
sentence Too expensive I'm going home LOL 6 times because there are 6 words
in the sentence. I also have a database that looks like this:

product_id  product price
1   Milk2.59
2   bread   1.05

And when $row is equal to 0 the output I get is
1 1 Milk Milk 2.59 2.59 Which is printed to the screen according to how many
rows are in the db I belive.

So my question is why this behavior? I was expecting something like a while
loop.



Code please.

--
Jim Lucas

http://www.cmsws.com/
http://www.cmsws.com/examples/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach

2012-10-15 Thread David McGlone
On Monday, October 15, 2012 08:21:23 PM you wrote:
 Bastien Koert
 
 On 2012-10-15, at 8:16 PM, David McGlone da...@dmcentral.net wrote:
  I've been sitting here playing around with foreach() and I'm wondering why
  I am getting these results. here's what I've been fooling around with.
  the code has no perticular meaning, but I noticed if the script fails, I
  get the sentence Too expensive I'm going home LOL 6 times because there
  are 6 words in the sentence. I also have a database that looks like this:
  
  product_idproductprice
  1Milk2.59
  2bread1.05
  
  And when $row is equal to 0 the output I get is
  1 1 Milk Milk 2.59 2.59 Which is printed to the screen according to how
  many rows are in the db I belive.
  
  So my question is why this behavior? I was expecting something like a
  while
  loop.
 
 Dave,
 
 Foreach is an iterator over an array. Your $row is a pointer to a db result
 set. If you were to pass the $row result set to the foreach as an array,
 you'd get what you think you should
 
 Www.php.net/foreach

Thanks Bastien.
Heres what I started with:

$result = mysql_query(SELECT * FROM items);
$row = mysql_fetch_array($result);
foreach($row as $rows){
$row = 0;
if($row == 0){
echo $rows;
} else{
echo Too expensive I'm going home LOL;
}
}

Here's what I ended up with after you gave me the advise:
$result = mysql_query(SELECT * FROM items);
  $rows = array();
  while($row = mysql_fetch_array($result))
   $rows[] = $row;
  foreach($rows as $row){
  $product = $row['product'];
  $price = $row['price'];
echo $product ;
echo $price ;


$justright = 0;
$toohigh = 5; //I was going to use this to check if the price was too high 
just so I could use an elseif in the exercise, 
but I realized that 
it would only work if the if() evaluated to 
false, which would be   
impossible. Ahhh pizz on it, it was fun anyway! 
:-)

if($justright = $price){
 echo Not bad. I'll buy it.br /;
  } else
 echo Too expensive I'm going home LOL ;
   
  }

It's a dumb script that makes no sense but I had a blast doing this. When 
things start coming together like this, it gets so gratifying. :-)

 -- 
David M.



Re: [PHP] [foreach] - is it proper to...

2012-05-31 Thread Daniel Brown
On Thu, May 31, 2012 at 12:48 PM, Tristan sunnrun...@gmail.com wrote:
 I'm using Zend Studio and it had a suggestion that I do a foreach as such

 foreach($entry as $entry){

 }

 which would be the same as `foreach ($entry)` --- a syntax
option that doesn't exist, but would be ideal.

 foreach($entries as $entry){

 }

I prefer this method as well, as redefining a variable with its
own name, whether in a foreach loop or elsewhere, not only feels
clunky, but could also quite easily cause issues.  Imagine, for
example, that not all versions of PHP support the same-variable
option, be it by bug, deprecation, et cetera.  It would be a pain to
track down the bug in your code.

 they both seem to work but, from a readability standpoint and just makes
 more sense to me to use method 2. Is it bad practice to go with the 1st
 method of coding or preferred?

To be honest, I didn't know Zend was suggesting that, but if you
want my lowly opinion --- use the second (and your preferred) method.
I can't think of an instance in my experience where I found another
programmer's code using the first method either.

-- 
/Daniel P. Brown
Network Infrastructure Manager
http://www.php.net/

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] [foreach] - is it proper to...

2012-05-31 Thread Tristan
Thanks, well that's why I was asking because we just let a guy go for doing
stuff like that among other obvious bad coding issues and terrible logic.
The guy didn't know what he was doing but, I wanted to make sure I wasn't
out of my mind by pointing that out. I am new to Zend Studio so I don't
know if it was picking that up from other bad code in the project and
suggesting for consistency sake or what. I definitely thought it was
weird.

Thanks again.

On Thu, May 31, 2012 at 10:54 AM, Daniel Brown danbr...@php.net wrote:

 On Thu, May 31, 2012 at 12:48 PM, Tristan sunnrun...@gmail.com wrote:
  I'm using Zend Studio and it had a suggestion that I do a foreach as such
 
  foreach($entry as $entry){
 
  }

  which would be the same as `foreach ($entry)` --- a syntax
 option that doesn't exist, but would be ideal.

  foreach($entries as $entry){
 
  }

I prefer this method as well, as redefining a variable with its
 own name, whether in a foreach loop or elsewhere, not only feels
 clunky, but could also quite easily cause issues.  Imagine, for
 example, that not all versions of PHP support the same-variable
 option, be it by bug, deprecation, et cetera.  It would be a pain to
 track down the bug in your code.

  they both seem to work but, from a readability standpoint and just makes
  more sense to me to use method 2. Is it bad practice to go with the 1st
  method of coding or preferred?

 To be honest, I didn't know Zend was suggesting that, but if you
 want my lowly opinion --- use the second (and your preferred) method.
 I can't think of an instance in my experience where I found another
 programmer's code using the first method either.

 --
 /Daniel P. Brown
 Network Infrastructure Manager
 http://www.php.net/



Re: [PHP] [foreach] - is it proper to...

2012-05-31 Thread Tedd Sperling
On May 31, 2012, at 12:48 PM, Tristan wrote:

 I'm using Zend Studio and it had a suggestion that I do a foreach as such
 
 foreach($entry as $entry){
 
 }
 
 instead of
 
 foreach($entries as $entry){
 
 }
 
 they both seem to work but, from a readability standpoint and just makes
 more sense to me to use method 2. Is it bad practice to go with the 1st
 method of coding or preferred?
 
 Thanks, T

Let's look at that.

In the first case you're doing a foreach loop on an array entitled $entry 
(single) using a variable entitled the same name representing the values in 
each element of the array  -- that doesn't make sense even if it works or is 
recommended by Zend Studio. That would be a hell of a bug to find.

In the second case, I find the syntax more correct. You are doing a foreach 
loop on an array entitled $entries (plural) using the values contained in the 
array as $entry (single) -- that makes much more sense to me.

My $0.02

Cheers,

tedd
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] [foreach] - is it proper to...

2012-05-31 Thread Mackintosh, Mike
-Original Message-
From: Tedd Sperling [mailto:t...@sperling.com] 
Sent: Thursday, May 31, 2012 1:01 PM
To: php-general General
Cc: Tristan
Subject: Re: [PHP] [foreach] - is it proper to...

On May 31, 2012, at 12:48 PM, Tristan wrote:

 I'm using Zend Studio and it had a suggestion that I do a foreach as 
 such
 
 foreach($entry as $entry){
 
 }
 
 instead of
 
 foreach($entries as $entry){
 
 }
 
 they both seem to work but, from a readability standpoint and just 
 makes more sense to me to use method 2. Is it bad practice to go with 
 the 1st method of coding or preferred?
 
 Thanks, T


But don't forget, the first scenario would be bad coding practice; you
are mutating the array $entry. It will become the last value of the
array you are foreach'ing. $entry begins as an array, and ends as a
string. As a result, I'd suggest to stay away from it. 

The second scenario, $ entries remains an array, and $entry a string.
Thanks,

Mike

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach

2012-04-06 Thread tamouse mailing lists
On Thu, Apr 5, 2012 at 3:15 PM, Ethan Rosenberg eth...@earthlink.net wrote:
 I know I am missing something fundamental - but I have no idea where to
 start to look.

It's really difficult to figure out what you're asking. Your code
snippets and associated output seem all jumbled up. It would help
greatly if they were presented in order.

 Here are code snippets:

 I have truncated the allowed_fields to make it easier to debug.

  $allowed_fields = array(  'Site' ='POST[Site]', 'MedRec' = 
 '$_POST[MedRec]', 'Fname' = '$_POST[Fname]'   );
  echo post #1\n;
  print_r($_POST);

Here, do you realize that you are setting each element of the array to
the exact contents of each string, i.e., there will be no variable
interpolation? If that's what you intend to do, great, but read on...


 RESPONSE:

  post #1
 Array
 (
    [Site] = AA
    [MedRec] = 10002
    [Fname] =
    [Lname] =
    [Phone] =
    [Height] =
    [welcome_already_seen] = already_seen
    [next_step] = step10
 )

Are you expecting something else here, or is the $_POST containing the
correct data?


 // $allowed_fields = array(Site, MedRec, Fname, Lname, // previous 
 statement of $allowed_fields
 // Phone, Sex, Height);

I'm not clear why you're showing commented out lines.

This looks like output from a statement below. It's much clearer if
you put the output below the code.

 Key Site, Value POST[Site]
 Key MedRec, Value $_POST[MedRec]
 Key Fname, Value $_POST[Fname]

 foreach ($allowed_fields as $key = $val) {
print Key $key, Value $val\n;
 }

And the above output is exactly what I would expect given how you
created the $allowed_fields hash: each of the values was set as an
uninterpolated string by using single quotes instead of double quotes.
If you really wanted the values, you should not have quoted them at
all, but instead quoted the $_POST key names, like so:

$allowed_fields =
   array('Site'   = $_POST['Site'],
 'MedRec' = $_POST['MedRec'],
 'Fname'  = $_POST['Fname']);

Pay closer attention to what you are quoting and how you are quoting it.


 if(isset($_Request['Sex']) trim($_POST['Sex']) != '' )

$_REQUEST is always fully capitalizes, unless it's your own variable.
(If it is, I suggest using another name as it's confusing.) Also, as
you seem to know that the field is in the $_POST array, rather than
use $_REQUEST, go ahead and just use $_POST.

 {
   if ($_REQUEST['Sex'] === 0)
   {
 $sex = 'Male';
   }
   else
   {
 $sex = 'Female';
   }
 }

This is an opportune time to use a ternary operator. Replace the inner
if-else with:

$sex = ($_POST['Sex'] === 0) ? 'Male' : 'Female' ;

  }

^ Is this an extra closing brace or is it closing something before the
snippet? (confusing)

 echo Post#2;
 print_r($_POST);
 if(empty($allowed_fields))

What is happening after this line?


 //RESPONSE

 Post#2Array
 (
   [Site] = AA
   [MedRec] = 10002
   [Fname] =
   [Lname] =
   [Phone] =
   [Height] =
   [welcome_already_seen] = already_seen
   [next_step] = step10
 )

As you have not changed $_POST in any way, this is exactly what you
should expect to see.

 {
  echo ouch;
 }

Is this ^^  what comes after the if(empty statement above? What is it's output?

 foreach ( $allowed_fields as $key = $val ) //This is line 198
 {
  if ( ! empty( $_POST['val'] ) )

This will always check the value associated with the 'val' entry in
$_POST. I'm pretty sure this is not what you want.

  {
   print Key $key, Value $val\n;
   $cxn = mysqli_connect($host,$user,$password,$db);
   $value = mysql_real_escape_string( $_POST[$fld] );
   $query .=  AND $fld = '$_POST[value]' ;

The query will check to see if what ever $fld evaluates to (I don't
see where it is set, but maybe somewhere else) and compare it to the
*exact* string $_POST[value] -- I doubt that you are storing that in
your data base -- at this point I'm not really sure what you want
there.

   echo #1 $query; //never echos the query

^^ it never will, since the Notice and Warning below indicate the for
loop is never executed.

  }
 }

 These are the messages I receive on execution of the script:

 Notice: Undefined variable: allowed_fields in /var/www/srchrhsptl5.php on
 line 198
 Warning: Invalid argument supplied for foreach() in /var/www/srchrhsptl5.php
 on line 198

Is this stretch of code inside a function perhaps? If so, is
$allowed_fields declared as a global inside the function? Please send
or pastebin more code so we can see it clearly. Generally when a
problem like that is reported and it's not obviously a typo or
spelling error, the problem is not necessarily at the line itself, but
above someplace in the code.

 Advice and help, please.

My general advice is to pay closer attention to what you're quoting
and how you're quoting it, and that case matters in variable names.

'$_POST[val]' is the *exact* string '$_POST[val]' -- it does not get
any content from the $_POST variable or one of it's fields. Please
*READ AGAIN* about quoting and variable interpolation: 

RE: [PHP] foreach weirdness

2012-03-26 Thread Arno Kuhl
Requesting that will at least require a major-release (f.e. PHP 6.0) ... but I 
would rather request to add a notice or warning to the documentation of 
references to remind stuff like that.
http://www.php.net/manual/en/language.references.php
I think this is stuff more people will stumble over ...

Bye
Simon
--

I agree it would be wrong to change php's handling of call by reference in 
foreach loops because there may be a need to access that reference after 
completing the loop. I was going to suggest there should be a warning in the 
manual to unset the reference after the foreach loop is completed, but I see 
the current online manual has that warning prominently displayed on the foreach 
page. I had a version of the manual from July last year that didn't have the 
warning, so I'll update my local manual and make sure I keep it up to date. 
Lesson learned (both manual and foreach references).

Cheers
Arno


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] foreach weirdness

2012-03-26 Thread Arno Kuhl
Note that somewhat similar error was discussed on this list a few months 
ago[1]. You could probably have solved it yourself if you searched the mailing 
list archives.

- Matijn

[1] http://www.mail-archive.com/php-general@lists.php.net/msg269552.html
---

Thanks Matijn, I missed that discussion, not following the list that actively. 
I'll try search next time before raising an issue.

Cheers
Arno


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] foreach weirdness

2012-03-25 Thread Arno Kuhl
 See this following example that illustrates the problem:
 $array = array(0, 1, 2, 3, 4, 5, 6);
 foreach ($array as $index=$value) { 
   if ( ($index+1)  count($array) ) { 
   $array[$index+1] += $value; 
   } 
   echo $value. ;
 }
 echo br /;
 foreach ($array as $index=$value) { 
   echo $value. ;
 }
 
 You'd expect the output to be: 
 0 1 3 6 10 15 21
 0 1 3 6 10 15 21
 
 But it's actually: 
 0 1 2 3 4 5 6
 0 1 3 5 7 9 11

Hey,

the ouput you get is right. If you want your ouput you have to rewrite your 
code.
Currently you are adding the value of the current index to the next indexes 
value (e.g. $array[0] + $array[1]; $array[1] + $array[2]; etc.).
As I understand it you want to add the current value with the next index (e.g. 
$array[0] + 1; $array[1] + 2; $array[2] + 3).
--

Hi Stephan, the first foreach loop adds the next value to the current value, 
not the next index. The reason you don't get the expected result in the first 
foreach loop is because you need to assign the $value by reference, as per the 
php manual
foreach ($array as $index=$value) 

But then to get the correct output from the second simple foreach loop, you 
also have to assign the $value by reference, contrary to the php manual. If you 
don't you get the wrong result and the array becomes corrupted. That could be 
classified as a bug, or at least the manual needs to elaborate on using a 
foreach when you assign the $value by reference.

Cheers
Arno


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] foreach weirdness

2012-03-25 Thread Arno Kuhl
From: Simon Schick [mailto:simonsimc...@googlemail.com] 
Sent: 24 March 2012 12:30 AM
To: Robert Cummings
Cc: a...@dotcontent.net; php-general@lists.php.net
Subject: Re: [PHP] foreach weirdness

2012/3/23 Robert Cummings rob...@interjinn.com

 On 12-03-23 11:16 AM, Arno Kuhl wrote:


 it still does not produce the correct result:
 0 1 3 6 10 15 21
 0 1 3 6 10 15 15


 This looks like a bug... the last row should be the same. What version 
 of PHP are you using? Have you checked the online bug reports?



Hi, Robert

Does not seem like a bug to me ...
http://schlueters.de/blog/archives/141-References-and-foreach.html

What you should do to get the expected result:
Unset the variable after you don't need this reference any longer.

Bye
Simon

--

Hi Simon, unsetting the $value does fix the problem, but I found that any time 
you assign $value by reference in a foreach loop you have to do an unset to 
avoid corrupting the array unless you continue to assign $value by reference 
(as illustrated in the article you linked).
 
So doing something as simple as:
$array = array(0, 1, 2, 3, 4, 5, 6);
foreach ($array as $key=$value) {
echo Key: $key; Value: $valuebr /\n;
}

and then follow with (from the php manual):
foreach ($array as $key=$value) {
echo Key: $key; Value: $valuebr /\n;
}

will not only give the wrong result, it will corrupt the array for *any* 
further use of that array. I still think it’s a bug according to the definition 
of foreach in the php manual. Maybe php needs to do an implicit unset at the 
closing brace of the foreach where was an assign $value by reference, to remove 
the reference to the last element (or whatever element it was pointing to if 
there was a break) so that it doesn't corrupt the array, because any assign to 
$value after the foreach loop is completed will corrupt the array (confirmed by 
testing). The average user (like me) wouldn't think twice about reusing $value 
after ending the foreach loop, not realising that without an unset the array 
will be corrupted.

BTW thanks for that reference, it was quite an eye-opener on the pitfalls of 
using assign by reference, not only in the foreach loop.

Cheers
Arno


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach weirdness

2012-03-25 Thread Matijn Woudt
On Sun, Mar 25, 2012 at 4:11 PM, Arno Kuhl a...@dotcontent.net wrote:
 From: Simon Schick [mailto:simonsimc...@googlemail.com]
 Sent: 24 March 2012 12:30 AM
 To: Robert Cummings
 Cc: a...@dotcontent.net; php-general@lists.php.net
 Subject: Re: [PHP] foreach weirdness

 2012/3/23 Robert Cummings rob...@interjinn.com

 On 12-03-23 11:16 AM, Arno Kuhl wrote:


 it still does not produce the correct result:
 0 1 3 6 10 15 21
 0 1 3 6 10 15 15


 This looks like a bug... the last row should be the same. What version
 of PHP are you using? Have you checked the online bug reports?



 Hi, Robert

 Does not seem like a bug to me ...
 http://schlueters.de/blog/archives/141-References-and-foreach.html

 What you should do to get the expected result:
 Unset the variable after you don't need this reference any longer.

 Bye
 Simon

 --

 Hi Simon, unsetting the $value does fix the problem, but I found that any 
 time you assign $value by reference in a foreach loop you have to do an unset 
 to avoid corrupting the array unless you continue to assign $value by 
 reference (as illustrated in the article you linked).

 So doing something as simple as:
 $array = array(0, 1, 2, 3, 4, 5, 6);
 foreach ($array as $key=$value) {
        echo Key: $key; Value: $valuebr /\n;
 }

 and then follow with (from the php manual):
 foreach ($array as $key=$value) {
        echo Key: $key; Value: $valuebr /\n;
 }

 will not only give the wrong result, it will corrupt the array for *any* 
 further use of that array. I still think it’s a bug according to the 
 definition of foreach in the php manual. Maybe php needs to do an implicit 
 unset at the closing brace of the foreach where was an assign $value by 
 reference, to remove the reference to the last element (or whatever element 
 it was pointing to if there was a break) so that it doesn't corrupt the 
 array, because any assign to $value after the foreach loop is completed will 
 corrupt the array (confirmed by testing). The average user (like me) wouldn't 
 think twice about reusing $value after ending the foreach loop, not realising 
 that without an unset the array will be corrupted.

 BTW thanks for that reference, it was quite an eye-opener on the pitfalls of 
 using assign by reference, not only in the foreach loop.

 Cheers
 Arno

Note that somewhat similar error was discussed on this list a few
months ago[1]. You could probably have solved it yourself if you
searched the mailing list archives.

- Matijn

[1] http://www.mail-archive.com/php-general@lists.php.net/msg269552.html

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach weirdness

2012-03-25 Thread Simon Schick
2012/3/25 Arno Kuhl a...@dotcontent.net:

 will not only give the wrong result, it will corrupt the array for *any* 
 further use of that array. I still think it’s a bug according to the 
 definition of foreach in the php manual. Maybe php needs to do an implicit 
 unset at the closing brace of the foreach where was an assign $value by 
 reference, to remove the reference to the last element (or whatever element 
 it was pointing to if there was a break) so that it doesn't corrupt the 
 array, because any assign to $value after the foreach loop is completed will 
 corrupt the array (confirmed by testing). The average user (like me) wouldn't 
 think twice about reusing $value after ending the foreach loop, not realising 
 that without an unset the array will be corrupted.


Hi, Arno

Requesting that will at least require a major-release (f.e. PHP 6.0)
... but I would rather request to add a notice or warning to the
documentation of references to remind stuff like that.
http://www.php.net/manual/en/language.references.php
I think this is stuff more people will stumble over ...

Bye
Simon

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach weirdness

2012-03-24 Thread Al



On 3/23/2012 10:11 PM, Robert Cummings wrote:

On 12-03-23 06:30 PM, Simon Schick wrote:

2012/3/23 Robert Cummingsrob...@interjinn.com


On 12-03-23 11:16 AM, Arno Kuhl wrote:



it still does not produce the correct result:
0 1 3 6 10 15 21
0 1 3 6 10 15 15



This looks like a bug... the last row should be the same. What version of
PHP are you using? Have you checked the online bug reports?




Hi, Robert

Does not seem like a bug to me ...
http://schlueters.de/blog/archives/141-References-and-foreach.html

What you should do to get the expected result:
Unset the variable after you don't need this reference any longer.


Ah yes... that clued me in. I disagree with the article's generalization with
respect to references since references accomplish some things that cannot be
accomplished otherwise, but even I missed the fact that the second loop was
using a variable that was a reference to the last element of the array as
created in the first loop *lol*. The user's very act of checking their results
was confounding the result... I love it :)

Cheers,
Rob.


Re, your ...that cannot be accomplished otherwise,... Can you provide some 
examples?  The only ones I've found are when using create_function() and the 
arguments for callback functions. I can't even remember or find in my code an 
example of my foreach()loops needed it. Seems, I recall earlier versions of PHP 
[4? ]required references for variables.


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach weirdness

2012-03-24 Thread Robert Cummings

On 12-03-24 11:15 AM, Al wrote:



On 3/23/2012 10:11 PM, Robert Cummings wrote:

On 12-03-23 06:30 PM, Simon Schick wrote:

2012/3/23 Robert Cummingsrob...@interjinn.com


On 12-03-23 11:16 AM, Arno Kuhl wrote:



it still does not produce the correct result:
0 1 3 6 10 15 21
0 1 3 6 10 15 15



This looks like a bug... the last row should be the same. What version of
PHP are you using? Have you checked the online bug reports?




Hi, Robert

Does not seem like a bug to me ...
http://schlueters.de/blog/archives/141-References-and-foreach.html

What you should do to get the expected result:
Unset the variable after you don't need this reference any longer.


Ah yes... that clued me in. I disagree with the article's generalization with
respect to references since references accomplish some things that cannot be
accomplished otherwise, but even I missed the fact that the second loop was
using a variable that was a reference to the last element of the array as
created in the first loop *lol*. The user's very act of checking their results
was confounding the result... I love it :)

Cheers,
Rob.


Re, your ...that cannot be accomplished otherwise,... Can you provide some
examples?  The only ones I've found are when using create_function() and the
arguments for callback functions. I can't even remember or find in my code an
example of my foreach()loops needed it. Seems, I recall earlier versions of PHP
[4? ]required references for variables.


After I submitted ...that cannot be accomplished otherwise,..., I 
realized it was a patently false statement (a turing machine is a turing 
machine :). The intent of the statement though was to indicate the 
greater difficulty in achieving something relatively simple with 
references. See the other thread Thinking out loud - continuation. My 
post dated 2012-03-24 00:24 shows a process that is cumbersome and 
inefficient to implement in another fashion. References are like 
pointers... very powerful but with cautions for the unwary.


Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach weirdness

2012-03-23 Thread Robert Cummings

On 12-03-23 11:16 AM, Arno Kuhl wrote:

The following snippet is copied from the php manual:
foreach ($arr as $key =  $value) {
echo Key: $key; Value: $valuebr /\n;
}

I've always used the foreach loop that way.
But recently I started hitting some really odd problems.

See this following example that illustrates the problem:
$array = array(0, 1, 2, 3, 4, 5, 6);
foreach ($array as $index=$value) {
if ( ($index+1)  count($array) ) {
$array[$index+1] += $value;
}
echo $value. ;
}
echo br /;
foreach ($array as $index=$value) {
echo $value. ;
}

You'd expect the output to be:
0 1 3 6 10 15 21
0 1 3 6 10 15 21

But it's actually:
0 1 2 3 4 5 6
0 1 3 5 7 9 11


This is what I would expect since the value is a copy. As such, one 
would expect it to be the value before you made modifications to the array.



If you assign the $value by reference in the first loop as someone pointed
out (and confirmed by the manual: As of PHP 5, you can easily modify
array's elements by preceding $value with. This will assign reference
instead of copying the value)

$array = array(0, 1, 2, 3, 4, 5, 6);
foreach ($array as $index=$value) {//- assign $value by reference
if ( ($index+1)  count($array) ) {
$array[$index+1] += $value;
}
echo $value. ;
}
echo br /;
foreach ($array as $index=$value) {
echo $value. ;
}

it still does not produce the correct result:
0 1 3 6 10 15 21
0 1 3 6 10 15 15


This looks like a bug... the last row should be the same. What version 
of PHP are you using? Have you checked the online bug reports?



If I watch the $array in a debugger I see odd behaviour for the last element
$array[6] when stepping through the second foreach loop.
Just before entering the second loop $array[6] == 21 which is correct.
When I move to the next line (echo $value. ;)  $array[6] changes to 0 !!
As I step through the second loop $array[6] keeps on changing for each
iteration, with the following values:
0, 1, 3, 6, 10, 15, 15
And once I've left the second loop $array[6] is permanently changed from 21
to 15, even though there's no code in the second loop to change $array[6].
So what's going on here?

I confirm this by echoing $array[6] in each iteration in the second loop:
$array = array(0, 1, 2, 3, 4, 5, 6);
foreach ($array as $index=$value) {
if ( ($index+1)  count($array) ) {
$array[$index+1] += $value;
}
echo $value. ;
}
echo br /;
foreach ($array as $index=$value) {
echo $array[6]. ;
}
echo br /;
echo $array[6];

the result is:
0 1 3 6 10 15 21
0 1 3 6 10 15 15
15

Note that $array[6] is still 15 even after completing the second foreach
loop.
If you break out of the second loop then $array[6] will be at whatever value
it was at the time you break out (ouch!)

If you assign the $value by reference in the second loop as well:
$array = array(0, 1, 2, 3, 4, 5, 6);
foreach ($array as $index=$value) {
if ( ($index+1)  count($array) ) {
$array[$index+1] += $value;
}
echo $value. ;
}
echo br /;
foreach ($array as $index=$value) {//- assign $value by reference
echo $array[6]. ;
}
echo br /;
echo $array[6];

you finally get the correct result:
0 1 3 6 10 15 21
21 21 21 21 21 21 21
21

You can test this with multiple foreach loops and get the same results. If
you modify the array in the first foreach loop, then use an assign $value by
reference in the next 9 foreach loops to get the correct values (without
modifying the array), and then in the 10th foreach loop you don't use an
assign $value by reference (without modifying the array), the array becomes
corrupted.

I sort of understand the need to assign the $value by reference in the first
loop, but why is it also required in every subsequent loop where the array
is not being modified? Especially since all the examples in the manual show
it's not needed? It would appear that once you've modified an array's
elements in a foreach loop you always have to assign $value by reference in
any subsequent foreach loop using that array. And if you don't, not only
will you get the wrong results but the array itself is actually altered,
even if there's no code in the loop to alter it. Is that correct or is it a
bug? At what stage can you start using the array in the normal way again?
That could create hair-pulling havoc for anyone maintaining code if they
haven't noticed that somewhere previously there was code that modified the
array in a foreach loop. Maybe the answer is to always assign $value by
reference in a foreach loop regardless of what you do in that loop, but I'm
not sure what the implications are.


Here's how you should do it (IMHO) to avoid all sorts of side effects, 
magic behaviour, and unnecessary complications:


?php

$array = array( 0, 1, 2, 3, 4, 5, 6 );
foreach( array_keys( $array ) as $index )
{
if( ($index + 1)  count( $array ) )
{
   

RE: [PHP] foreach weirdness

2012-03-23 Thread Arno Kuhl
-Original Message-
From: Robert Cummings [mailto:rob...@interjinn.com] 
Sent: 23 March 2012 06:11 PM
To: a...@dotcontent.net
Cc: php-general@lists.php.net
Subject: Re: [PHP] foreach weirdness

On 12-03-23 11:16 AM, Arno Kuhl wrote:
 The following snippet is copied from the php manual:
 foreach ($arr as $key =  $value) {
   echo Key: $key; Value: $valuebr /\n; }

 I've always used the foreach loop that way.
 But recently I started hitting some really odd problems.

 See this following example that illustrates the problem:
 $array = array(0, 1, 2, 3, 4, 5, 6);
 foreach ($array as $index=$value) {//- assign $value by reference
   if ( ($index+1)  count($array) ) {
   $array[$index+1] += $value;
   }
   echo $value. ;
 }
 echo br /;
 foreach ($array as $index=$value) {
   echo $value. ;
 }

 it still does not produce the correct result:
 0 1 3 6 10 15 21
 0 1 3 6 10 15 15

This looks like a bug... the last row should be the same. What version of PHP 
are you using? Have you checked the online bug reports?

.
--

Hi Rob

I'm using php 5.3.5. What result do you get when you run this code?
I haven't checked any bug reports, I'll google to see where I would do that.

Your code gets round the problem, but I was specifically referring to the use 
of foreach with its unexpected side-effects. There are a few different designs 
like look-ahead where it seemed the obvious way to go. I know I've used this 
type of foreach coding in the past, and have this nagging feeling there's a 
whole bunch of code just waiting to explode. I always just assumed it worked 
because it's pretty simple. I'd previously been caught out forgetting the 
assign by reference in the foreach loop that modified the array but I always 
caught it long before it went live, but I never considered having to also use 
assign by reference in subsequent foreach loops because it so obviously wasn't 
necessary. Now I'm searching through my scripts to see if there are any 
potential problems caused by this (already found one), and wondering what else 
I've done where I no longer have access to the sources.

BTW I'm told on another forum this issue has been discussed multiple times on 
this mailing list - did I miss it? Was there a resolution?

Cheers
Arno


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach weirdness

2012-03-23 Thread Robert Cummings

On 12-03-23 02:04 PM, Arno Kuhl wrote:

Hi Rob

I'm using php 5.3.5. What result do you get when you run this code?
I haven't checked any bug reports, I'll google to see where I would do that.

Your code gets round the problem, but I was specifically referring to the use 
of foreach with its unexpected side-effects.


I know... but when I first started doing things like what you tried to 
do, there were no references for foreach values and so I've just 
naturally been in the habit of explicitly accessing the values in the 
array by index. Apparently that will serve me well since my stuff won't 
blow up with this bug ;)



There are a few different designs like look-ahead where it seemed the obvious 
way to go. I know I've used this type of foreach coding in the past, and have 
this nagging feeling there's a whole bunch of code just waiting to explode. I 
always just assumed it worked because it's pretty simple. I'd previously been 
caught out forgetting the assign by reference in the foreach loop that modified 
the array but I always caught it long before it went live, but I never 
considered having to also use assign by reference in subsequent foreach loops 
because it so obviously wasn't necessary. Now I'm searching through my scripts 
to see if there are any potential problems caused by this (already found one), 
and wondering what else I've done where I no longer have access to the sources.

BTW I'm told on another forum this issue has been discussed multiple times on 
this mailing list - did I miss it? Was there a resolution?


I must have missed it too... but then I've not been very active in the 
past year or so :)


Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach weirdness

2012-03-23 Thread Simon Schick
2012/3/23 Robert Cummings rob...@interjinn.com

 On 12-03-23 11:16 AM, Arno Kuhl wrote:


 it still does not produce the correct result:
 0 1 3 6 10 15 21
 0 1 3 6 10 15 15


 This looks like a bug... the last row should be the same. What version of
 PHP are you using? Have you checked the online bug reports?



Hi, Robert

Does not seem like a bug to me ...
http://schlueters.de/blog/archives/141-References-and-foreach.html

What you should do to get the expected result:
Unset the variable after you don't need this reference any longer.

Bye
Simon

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach weirdness

2012-03-23 Thread Robert Cummings

On 12-03-23 06:30 PM, Simon Schick wrote:

2012/3/23 Robert Cummingsrob...@interjinn.com


On 12-03-23 11:16 AM, Arno Kuhl wrote:



it still does not produce the correct result:
0 1 3 6 10 15 21
0 1 3 6 10 15 15



This looks like a bug... the last row should be the same. What version of
PHP are you using? Have you checked the online bug reports?




Hi, Robert

Does not seem like a bug to me ...
http://schlueters.de/blog/archives/141-References-and-foreach.html

What you should do to get the expected result:
Unset the variable after you don't need this reference any longer.


Ah yes... that clued me in. I disagree with the article's generalization 
with respect to references since references accomplish some things that 
cannot be accomplished otherwise, but even I missed the fact that the 
second loop was using a variable that was a reference to the last 
element of the array as created in the first loop *lol*. The user's very 
act of checking their results was confounding the result... I love it :)


Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Foreach question

2011-07-06 Thread Dajka Tamás
And that's exactly how I did it :)

Since 'for' is traditionally pre-testing with excetuting the condition prior 
looping it's working well :)

Thanks for all the help!

Cheers,

Tamas

-Original Message-
From: Louis Huppenbauer [mailto:louis.huppenba...@gmail.com] 
Sent: Tuesday, July 05, 2011 5:47 PM
To: Robert Cummings
Cc: Dajka Tamás; php-general@lists.php.net
Subject: Re: [PHP] Foreach question

Just use count($arr) in your for-header, as it get's executed again
for each loop.

?php
   $arr = array(array('id'=1), array('id'=2));
for($i=0;$icount($arr);$i++) {
echo $arr[$i]['id'];
if($i  6) {
$arr[] = array('id' = $arr[$i]['id']+1);
}
}
?

2011/7/5 Robert Cummings rob...@interjinn.com:
 On 11-07-05 10:48 AM, Dajka Tamás wrote:

 Thanks, that was interesting :) I think I got one step further in
 understanding PHP :)

 BTW, I've changed the loop to 'for' and it's working well :)

 Can you show us your for loop? I'm not immediately sure how you use a for
 loop to traverse a growing number of entries in an array without either
 updating the extents of the traversal or using for( ; ; ) which is the same
 as while( 1 ). Or are you now using the low level array traversal functions
 like reset() and next()?

 Cheers,
 Rob.
 --
 E-Mail Disclaimer: Information contained in this message and any
 attached documents is considered confidential and legally protected.
 This message is intended solely for the addressee(s). Disclosure,
 copying, and distribution are prohibited unless authorized.

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Louis Huppenbauer
Hi there

I think that foreach in your first example just knowns that this
should be the last loop (as the array only contains 1 element at
start) and so stops there.
In your 2nd example however the first loop isn't the last, so the
array get's checked again, and now there's another element, so...

I think that's more or less normal behaviour.

Sincerely yours
Louis

2011/7/5 Dajka Tamas vi...@vipernet.hu:
 Hi all,



 I've bumped into an interesting thing with foreach. I really don't know, if
 this is normal working, or why it is, so I got curious.



 The script:



 foreach ( $cats as $c ) {

               echo $c['id'];

               if ( $c['id']  5 ) {

                              $c['id']++;

                              $cats[] = $c;

               }

 }



 Input 1:



 $cats = array( array( 'id' = 1 ) );



 Output 1:



 1



 Input 2:



 $cats = array( array( 'id' = 1 ), array( 'id' = 2 ) );



 Output 2:



 122334455





 Why is this? Is this normal behaviour?





 Thanks,



               Tamas



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Robert Cummings


On 11-07-05 09:40 AM, Dajka Tamas wrote:

Hi all,



I've bumped into an interesting thing with foreach. I really don't know, if
this is normal working, or why it is, so I got curious.



The script:



foreach ( $cats as$c ) {

echo $c['id'];

if ( $c['id']  5 ) {

   $c['id']++;

   $cats[] = $c;

}

}


That's a bizarre loop... you're feeding references to elements of the 
array back into the array over which the loop is iterating. If you 
REALLY want to do what you are doing, then do the following:


?php

foreach( array_keys( $cats ) as $key )
{
$c = $cats[$key];

echo $c['id'];

if( $c['id']  5 )
{
$c['id']++;
$cats[] = $c;
}
}

?

Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Louis Huppenbauer
Or maybe he tried to do the following?

?php
foreach ( $cats as$c ) {
   echo $c['id'];
   if ($c['id']  5) {
  $cats[] = array('id' = ($c['id'] + 1));
   }
}
?

2011/7/5 Robert Cummings rob...@interjinn.com:

 On 11-07-05 09:40 AM, Dajka Tamas wrote:

 Hi all,



 I've bumped into an interesting thing with foreach. I really don't know,
 if
 this is normal working, or why it is, so I got curious.



 The script:



 foreach ( $cats as$c ) {

                echo $c['id'];

                if ( $c['id']  5 ) {

                               $c['id']++;

                               $cats[] = $c;

                }

 }

 That's a bizarre loop... you're feeding references to elements of the array
 back into the array over which the loop is iterating. If you REALLY want to
 do what you are doing, then do the following:

 ?php

 foreach( array_keys( $cats ) as $key )
 {
    $c = $cats[$key];

    echo $c['id'];

    if( $c['id']  5 )
    {
        $c['id']++;
        $cats[] = $c;
    }
 }

 ?

 Cheers,
 Rob.
 --
 E-Mail Disclaimer: Information contained in this message and any
 attached documents is considered confidential and legally protected.
 This message is intended solely for the addressee(s). Disclosure,
 copying, and distribution are prohibited unless authorized.

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Foreach question

2011-07-05 Thread Dajka Tamás
Hi,

Yeah, I'm really want to do that, since I'm working with the elements of the 
original array ( skipped that part in sample code ).

I've tried your suggestion, but it gives the same result, so on just one input 
is just gives back '1'.

What troubles me, that foreach gives an inconsistent working. Why is 'foreach' 
checking element count at all and working differently with different element 
counts? That's not normal is my opinion. 'foreach' shouldn't do this:

if ( count($elements) == 1 ) then loop 1;
else loop normally;

and that's what is does now, since when it's more than one element it's working 
like a while loop, with checking the condition before ( and after ) every run. 
( if 'foreach' would check that the current run is the last one before 
executing the current loop, the results would be the same with each case )

Cheers,

Tamas

-Original Message-
From: Robert Cummings [mailto:rob...@interjinn.com] 
Sent: Tuesday, July 05, 2011 4:06 PM
To: Dajka Tamas
Cc: php-general@lists.php.net
Subject: Re: [PHP] Foreach question


On 11-07-05 09:40 AM, Dajka Tamas wrote:
 Hi all,



 I've bumped into an interesting thing with foreach. I really don't know, if
 this is normal working, or why it is, so I got curious.



 The script:



 foreach ( $cats as$c ) {

 echo $c['id'];

 if ( $c['id']  5 ) {

$c['id']++;

$cats[] = $c;

 }

 }

That's a bizarre loop... you're feeding references to elements of the 
array back into the array over which the loop is iterating. If you 
REALLY want to do what you are doing, then do the following:

?php

foreach( array_keys( $cats ) as $key )
{
 $c = $cats[$key];

 echo $c['id'];

 if( $c['id']  5 )
 {
 $c['id']++;
 $cats[] = $c;
 }
}

?

Cheers,
Rob.
-- 
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Foreach question

2011-07-05 Thread Dajka Tamás
Tried, gives the same result with one element :(

What's working:

$cats = array( array( 'id' = 1 ) );
while ( $c = array_shift($cats) ) {
echo $c['id'];
if ( $c['id']  5 ) {
$c['id']++;
$cats[] = $c;
}
}

But this is 'while' and it pops all elements from the array...

Cheers,

Tamas



-Original Message-
From: Louis Huppenbauer [mailto:louis.huppenba...@gmail.com] 
Sent: Tuesday, July 05, 2011 4:12 PM
To: Robert Cummings
Cc: Dajka Tamas; php-general@lists.php.net
Subject: Re: [PHP] Foreach question

Or maybe he tried to do the following?

?php
foreach ( $cats as$c ) {
   echo $c['id'];
   if ($c['id']  5) {
  $cats[] = array('id' = ($c['id'] + 1));
   }
}
?

2011/7/5 Robert Cummings rob...@interjinn.com:

 On 11-07-05 09:40 AM, Dajka Tamas wrote:

 Hi all,



 I've bumped into an interesting thing with foreach. I really don't know,
 if
 this is normal working, or why it is, so I got curious.



 The script:



 foreach ( $cats as$c ) {

echo $c['id'];

if ( $c['id']  5 ) {

   $c['id']++;

   $cats[] = $c;

}

 }

 That's a bizarre loop... you're feeding references to elements of the array
 back into the array over which the loop is iterating. If you REALLY want to
 do what you are doing, then do the following:

 ?php

 foreach( array_keys( $cats ) as $key )
 {
$c = $cats[$key];

echo $c['id'];

if( $c['id']  5 )
{
$c['id']++;
$cats[] = $c;
}
 }

 ?

 Cheers,
 Rob.
 --
 E-Mail Disclaimer: Information contained in this message and any
 attached documents is considered confidential and legally protected.
 This message is intended solely for the addressee(s). Disclosure,
 copying, and distribution are prohibited unless authorized.

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Robert Cummings

On 11-07-05 10:20 AM, Dajka Tamás wrote:

Hi,

Yeah, I'm really want to do that, since I'm working with the elements of the 
original array ( skipped that part in sample code ).

I've tried your suggestion, but it gives the same result, so on just one input 
is just gives back '1'.


Ahhh... you want the behaviour of the multiple elements... I presumed 
you wanted the other way around.



What troubles me, that foreach gives an inconsistent working. Why is 'foreach' 
checking element count at all and working differently with different element 
counts? That's not normal is my opinion. 'foreach' shouldn't do this:

if ( count($elements) == 1 ) then loop 1;
else loop normally;

and that's what is does now, since when it's more than one element it's working 
like a while loop, with checking the condition before ( and after ) every run. 
( if 'foreach' would check that the current run is the last one before 
executing the current loop, the results would be the same with each case )


You're making an assumption that it is checking the count. It may just 
be pre-determining whether another element exists for the next 
iteration. Consider the following pseudo code:


nextItem = items-reset();
while( nextItem )
{
item = nextItem;
nextItem = items-next();

// Do stuff.
}

There's lots of ways to program a loop... and your PHP foreach loop is 
being converted to something entirely different internally. The above 
doesn't count elements, but it will result in the same behaviour as you 
are experiencing.


Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Louis Huppenbauer
I don't think that it does this:

if ( count($elements) == 1 ) then loop 1;
else loop normally;

It's probably more something like that:

$i=count($elements);
loop:
$i--;
if($i == 0)
$last_loop = true;
else
$last_loop = false

if($last_loop)
   exit;
else
   goto loop;



But aside from that, I would propose you the same thing Robert already
did - Just use while or some other loop (for maybe?).

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




RE: [PHP] Foreach question

2011-07-05 Thread Dajka Tamás
Ok, but if it would be that way I shouldn't get '122334455' for second output, 
no? The item count increments with every iteration of the loop.

Or you're saying that, it checks for an existance of nextitem before every 
loop, and that will fail with just one element, but will always return true 
with two elements? ( since the first elements copy is pushed as third element, 
etc )


-Original Message-
From: Robert Cummings [mailto:rob...@interjinn.com] 
Sent: Tuesday, July 05, 2011 4:28 PM
To: Dajka Tamás
Cc: php-general@lists.php.net
Subject: Re: [PHP] Foreach question

On 11-07-05 10:20 AM, Dajka Tamás wrote:
 Hi,

 Yeah, I'm really want to do that, since I'm working with the elements of the 
 original array ( skipped that part in sample code ).

 I've tried your suggestion, but it gives the same result, so on just one 
 input is just gives back '1'.

Ahhh... you want the behaviour of the multiple elements... I presumed 
you wanted the other way around.

 What troubles me, that foreach gives an inconsistent working. Why is 
 'foreach' checking element count at all and working differently with 
 different element counts? That's not normal is my opinion. 'foreach' 
 shouldn't do this:

 if ( count($elements) == 1 ) then loop 1;
 else loop normally;

 and that's what is does now, since when it's more than one element it's 
 working like a while loop, with checking the condition before ( and after ) 
 every run. ( if 'foreach' would check that the current run is the last one 
 before executing the current loop, the results would be the same with each 
 case )

You're making an assumption that it is checking the count. It may just 
be pre-determining whether another element exists for the next 
iteration. Consider the following pseudo code:

 nextItem = items-reset();
 while( nextItem )
 {
 item = nextItem;
 nextItem = items-next();

 // Do stuff.
 }

There's lots of ways to program a loop... and your PHP foreach loop is 
being converted to something entirely different internally. The above 
doesn't count elements, but it will result in the same behaviour as you 
are experiencing.

Cheers,
Rob.
-- 
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Robert Cummings



On 11-07-05 10:39 AM, Dajka Tamás wrote:

Ok, but if it would be that way I shouldn't get '122334455' for second output, 
no? The item count increments with every iteration of the loop.

Or you're saying that, it checks for an existance of nextitem before every 
loop, and that will fail with just one element, but will always return true 
with two elements? ( since the first elements copy is pushed as third element, 
etc )


Exactly... it's not counting at all. If it were, you wouldn't get to so 
many iterations with only 2 entries in the array. I can't remember 
exactly how PHP stores arrays (some kind of bucket structure), but it's 
likely it traverses the items like a linked list using pointers from one 
to the next for efficiency.


Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Robert Cummings

On 11-07-05 10:39 AM, Dajka Tamás wrote:

Ok, but if it would be that way I shouldn't get '122334455' for second output, 
no? The item count increments with every iteration of the loop.

Or you're saying that, it checks for an existance of nextitem before every 
loop, and that will fail with just one element, but will always return true 
with two elements? ( since the first elements copy is pushed as third element, 
etc )


BTW, there are reasons you might calculate next item before iterating. 
If the current iteration removes the current item, then nextItem would 
still be valid (theoretically :). It's more often the case you might 
remove the current item, than try to remove the next item in a foreach 
iteration.


Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Robert Cummings

On 11-07-05 09:40 AM, Dajka Tamas wrote:


foreach ( $cats as$c ) {

echo $c['id'];

if ( $c['id']  5 ) {

   $c['id']++;

   $cats[] = $c;

}

}


Given that you seem to want the above functionality obtained when more 
than one element exists in the input array... the simplest way (I can 
bother to think up) to achieve what you want with little extra work is 
to do the following:


?php

$cats['_control_'] = null;
foreach ( $cats as $c )
{
if( $c === null )
{
continue;
}

echo $c['id'];

if ( $c['id']  5 )
{
$c['id']++;
$cats[] = $c;
}
}
unset( $cats['_control_'] );

?

Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Robert Cummings

On 11-07-05 10:48 AM, Dajka Tamás wrote:

Thanks, that was interesting :) I think I got one step further in understanding 
PHP :)

BTW, I've changed the loop to 'for' and it's working well :)


Can you show us your for loop? I'm not immediately sure how you use a 
for loop to traverse a growing number of entries in an array without 
either updating the extents of the traversal or using for( ; ; ) which 
is the same as while( 1 ). Or are you now using the low level array 
traversal functions like reset() and next()?


Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Stuart Dallas
On Tue, Jul 5, 2011 at 2:40 PM, Dajka Tamas vi...@vipernet.hu wrote:

 I've bumped into an interesting thing with foreach. I really don't know, if
 this is normal working, or why it is, so I got curious.

 The script:

 foreach ( $cats as $c ) {
 echo $c['id'];
 if ( $c['id']  5 ) {
$c['id']++;
$cats[] = $c;
 }
  }

 Input 1:

 $cats = array( array( 'id' = 1 ) );

 Output 1:

 1

 Input 2:

 $cats = array( array( 'id' = 1 ), array( 'id' = 2 ) );

 Output 2:

 122334455

 Why is this? Is this normal behaviour?


Looking at the implementation of foreach in the source, the pointer to the
next item in the array is calculated after evaluating the condition but
before executing that loop. Thus, with a single array element it decides
it's at the end of the array before the first loop. My C is a little rusty
so I might have the details slightly wrong, but that's the crux of what's
happening.

Whether that's normal and expected or a bug is one of the internals team,
but my guess is that it's a feature rather than a bug.

-Stuart

-- 
Stuart Dallas
3ft9 Ltd
http://3ft9.com/


Re: [PHP] Foreach question

2011-07-05 Thread Louis Huppenbauer
Just use count($arr) in your for-header, as it get's executed again
for each loop.

?php
   $arr = array(array('id'=1), array('id'=2));
for($i=0;$icount($arr);$i++) {
echo $arr[$i]['id'];
if($i  6) {
$arr[] = array('id' = $arr[$i]['id']+1);
}
}
?

2011/7/5 Robert Cummings rob...@interjinn.com:
 On 11-07-05 10:48 AM, Dajka Tamás wrote:

 Thanks, that was interesting :) I think I got one step further in
 understanding PHP :)

 BTW, I've changed the loop to 'for' and it's working well :)

 Can you show us your for loop? I'm not immediately sure how you use a for
 loop to traverse a growing number of entries in an array without either
 updating the extents of the traversal or using for( ; ; ) which is the same
 as while( 1 ). Or are you now using the low level array traversal functions
 like reset() and next()?

 Cheers,
 Rob.
 --
 E-Mail Disclaimer: Information contained in this message and any
 attached documents is considered confidential and legally protected.
 This message is intended solely for the addressee(s). Disclosure,
 copying, and distribution are prohibited unless authorized.

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach question

2011-07-05 Thread Robert Cummings

On 11-07-05 11:46 AM, Louis Huppenbauer wrote:

Just use count($arr) in your for-header, as it get's executed again
for each loop.

?php
$arr = array(array('id'=1), array('id'=2));
 for($i=0;$icount($arr);$i++) {
 echo $arr[$i]['id'];
 if($i  6) {
 $arr[] = array('id' =  $arr[$i]['id']+1);
 }
 }
?



Ok, so the extents are being updated on each pass of the loop :)

Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach insert error

2009-10-07 Thread Jim Lucas
Haig Davis wrote:
 Hello All,
 
 I have spent the entire day trying to get my calendar app to function
 correctly ---  I have no problem with the actual functioning of the
 calendar. What is giving me trouble is for each calendar day the user has
 the option to check a checkbox requesting the day off and additionally the
 user must select a weighting for the request i.e. 1-31 with 1 being 1st
 choice and 31 being their least desirable request. The request is then
 insered into a mysql database.
 
 I am relativly new to PHP so I may well be on the complete wrong track here.
 so far I have tried imploding the array  posting an associative array.
 
 Form Script:
 
 div class=workspace
 ?php
 if(isset($_POST['submit'])){
 
 $userID = mysql_real_escape_string(trim($userID));
 $year = mysql_real_escape_string(trim($_GET['year']));
 $month = mysql_real_escape_string(trim($_GET['mon']));
 $dayoff = $_POST['dayoff'];
 $weighting = mysql_real_escape_string(trim($_POST['weight']));
 var_dump($dayoff);
 
 foreach ($dayoff as
 $day){ //come back
 to this when figured out that inserting day works to inser wieghting
 
 $sql = INSERT INTO dayoff (userID, month, year, day) VALUES
 ('$userID', '$year', '$month', '$day');
 
 $q = mysql_query($sql)
 or die ('error making request');
 }
 
 
  }
 ?
 div class=form
 form name=form method=post action=?php $_SERVER['PHP_SELF'] ; ?
 h2Request Day Off/h2br /br /
 ?php include '../includes/dayoffcalendar.php' ; ?
 
 br /br /br /
 button type=submit name=submit value=Submit
 class=buttonSubmit/button
 button type=reset class=buttonReset/button
 /form
 
 Calendar Script:
 
 

I see a number of typo's in the following code.


 for($i = 1; $i = $last['mday']; $i++){
if($i == $today['mday']  $first['mon'] == $today['mon'] 
 $first['year'] == $today['year']){
   $style = 'today';
}
else{
   $style = 'day';
}

What are you trying to do here?

Should this...
$filename=$1.['month'].['year'];

Be this...
$filename=$i.['month'].['year'];

Plus, where are you actually using the previous line at?

echo '  div class=' . $style . '' . $i . 'br /br /' ; // creates
 comment box for points and check box for request day off
echo '  labelsmallPoint Weighting: /small/labelinput type=text
 name=weight$i[] size =3 maxlength=3 /Br /br / ';

Should you have weight$i[] in the previous line?  This will break a few things
I think.

echo '  labelsmallCheck Day Off: /small/labelinput type
 =checkbox name=dayoff[] value=\. $i . \ /br / ';
echo '  /div' . \n;
 
}

Over all, simply put, if you do not number the indexes of your array, you will
not be able to have a 1 to 1 association in your submitted array(s)

BTW: I would try and use the heredoc syntax in your example...  Makes things way
cleaner!

echo DAY

div class={$style}{$i}br /br /
labelsmallPoint Weighting: /small/label
input type=text name=days[{$i}][weight] size =3 maxlength=3 /Br 
/br /
labelsmallCheck Day Off: /small/label
input type=checkbox name=days[{$i}][dayoff] value={$i} /br /
/div

DAY;


Now, on your input side.  Try it a few times to see what you get and I think you
will be able to figure out how to eliminate the days that were not selected /
checked.

 
 I appreciate any advice that you may have. Thank you very much in advance,
 my head hurts and I've googled for a few hours with no joy.
 
 Thanks
 
 Haig
 


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach insert error

2009-10-07 Thread Paul M Foster
On Wed, Oct 07, 2009 at 03:31:14PM -0700, Haig Davis wrote:

 Hello All,
 
 I have spent the entire day trying to get my calendar app to function
 correctly ---  I have no problem with the actual functioning of the
 calendar. What is giving me trouble is for each calendar day the user has
 the option to check a checkbox requesting the day off and additionally the
 user must select a weighting for the request i.e. 1-31 with 1 being 1st
 choice and 31 being their least desirable request. The request is then
 insered into a mysql database.
 
 I am relativly new to PHP so I may well be on the complete wrong track here.
 so far I have tried imploding the array  posting an associative array.

You don't actually saw what your real problem is, and I'm too lazy (and
tired) to try to figure it out from your code. Can you elaborate?

Paul

-- 
Paul M. Foster

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-08-01 Thread Andrew Ballard
On Fri, Jul 31, 2009 at 4:51 PM, Miller,
Teriontmil...@springfi.gannett.com wrote:
 //Show all restaurants that start with $letter not
 between A and Z

 $other = ctype_digit($letter);

 foreach(range('0','9') as $other) {

 $sql = SELECT  DISTINCT ID, name, address
 FROMrestaurants
 WHERE   name LIKE '{$other}%' ;

 $result = mysql_query($sql) or die(mysql_error());

 while($row = mysql_fetch_assoc($result)){

 $name = $row['name'];

 printf(
 'a href=view.php?ID=%sb%s/bbr /%s'
 . 'br /br //a',
 $row['ID'],
 $row['name'],
 $row['address']
 );
 }
 }


Why are you running 10 individual queries to search for restaurants
whose name begins with a number?

There are (at least) two simple, sargable alternatives available that
will work in MySQL to do the work in one shot:

SELECT  DISTINCT ID, name, address
FROMrestaurants
WHERE   name LIKE '0%'
   OR   name LIKE '1%'
   OR   name LIKE '2%'
   OR   name LIKE '3%'
   OR   name LIKE '4%'
   OR   name LIKE '5%'
   OR   name LIKE '6%'
   OR   name LIKE '7%'
   OR   name LIKE '8%'
   OR   name LIKE '9%'

(It can use an index on the `name` column and it works, but it's
pretty verbose. Performance might suffer a little if it involves a
table scan because of the OR's, but I'm not sure about that.)

SELECT  DISTINCT ID, name, address
FROMrestaurants
WHERE   name = '0' AND name  'A';

(Its a lot shorter because it takes advantage of string collation. Any
string that begins with the character '0' will be greater than (or
equal if the string is exactly '0') than '0'.)


Also, if your table is set up correctly, you do not need the DISTINCT
keyword in your query. Each restaurant should appear exactly once in
the `restaurants` table.

And just for fun... do you have any restaurants in your list whose
name begins with a punctuation mark or some other non-alphanumeric
character?  :-)


Andrew

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Bastien Koert
On Fri, Jul 31, 2009 at 12:53 PM, Miller,
Teriontmil...@springfi.gannett.com wrote:




 I have this script that works, just a couple tweeks needed...

 1. I don't want it to default to A being selected
 2. I need the number range part to only display one # sign not 10 of them,
 somehow I have to have it pull any record that does not start with alpha


   ?php
                                                          $letter =
 isset($_GET['letter']) ? $_GET['letter'] :A;

                                                        echo 'div
 align=centerb';

 foreach(range('A','Z') as $c){
                                                          ($letter == $c)
                                                            ?
 printf('%snbsp',$c)
                                                            : printf('a
 href=browse.php?letter=%s%s/anbsp;',$c,$c);
                                                        }

                                                        echo 'br';
                                                        //Other


 foreach(range('0','9') as $n){
                                                          ($letter == $n)
                                                        ?
 printf('%snbsp',$n)
                                                        : printf('a
 href=?letter=%s#/anbsp;',$n,$n);
                                                      }

                                                        echo
 /bbr/divp;

                              ?


 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php



How about


?php
 $letter = isset($_GET['letter']) ? $_GET['letter'] :;

 echo 'div align=centerb';

 foreach(range('A','Z') as $c){
   ($letter == $c) ? printf('%snbsp',$c) : printf('a
href=browse.php?letter=%s%s/anbsp;',$c,$c);
 }

 echo 'br';

 //Other
 $bNumberShown = false;
 foreach(range('0','9') as $n){
   if($letter == $n) {
 printf('%snbsp',$n)
   }else{
 if ($bNumberShown){
   printf('a href=?letter=%s%s/anbsp;',$n,$n);
 }else{
   printf('a href=?letter=%s#%s/anbsp;',$n,$n);
   $bNumberShown = true;
 }
 }

  echo /bbr/divp;

?

-- 

Bastien

Cat, the other other white meat

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Miller, Terion



On 7/31/09 12:27 PM, Bastien Koert phps...@gmail.com wrote:

$letter = isset($_GET['letter']) ? $_GET['letter'] :;

 echo 'div align=centerb';

 foreach(range('A','Z') as $c){
   ($letter == $c) ? printf('%snbsp',$c) : printf('a
href=browse.php?letter=%s%s/anbsp;',$c,$c);
 }

 echo 'br';

 //Other
 $bNumberShown = false;
 foreach(range('0','9') as $n){
   if($letter == $n) {
 printf('%snbsp',$n)
   }else{
if ($bNumberShown){
   printf('a href=?letter=%s%s/anbsp;',$n,$n);
 }else{
   printf('a href=?letter=%s#%s/anbsp;',$n,$n);
   $bNumberShown = true;
 }
 }

  echo /bbr/divp;

Looks like it would work but I keep getting syntax error unexpected { at the 
first
 }else{
I have tried to move the brackets around but it just moves the error

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Bastien Koert
On Fri, Jul 31, 2009 at 1:40 PM, Miller,
Teriontmil...@springfi.gannett.com wrote:



 On 7/31/09 12:27 PM, Bastien Koert phps...@gmail.com wrote:

 $letter = isset($_GET['letter']) ? $_GET['letter'] :;

  echo 'div align=centerb';

  foreach(range('A','Z') as $c){
   ($letter == $c) ? printf('%snbsp',$c) : printf('a
 href=browse.php?letter=%s%s/anbsp;',$c,$c);
  }

  echo 'br';

  //Other
  $bNumberShown = false;
  foreach(range('0','9') as $n){
   if($letter == $n) {
     printf('%snbsp',$n)
   }else{
    if ($bNumberShown){
       printf('a href=?letter=%s%s/anbsp;',$n,$n);
     }else{
       printf('a href=?letter=%s#%s/anbsp;',$n,$n);
       $bNumberShown = true;
     }
  }

  echo /bbr/divp;

 Looks like it would work but I keep getting syntax error unexpected { at the 
 first
  }else{
 I have tried to move the brackets around but it just moves the error


My bad, missed a closing curly brace on the foreach loop

?php
 $letter = isset($_GET['letter']) ? $_GET['letter'] :;

 echo 'div align=centerb';

 foreach(range('A','Z') as $c){
   ($letter == $c) ? printf('%snbsp',$c) : printf('a
href=browse.php?letter=%s%s/anbsp;',$c,$c);
 }

 echo 'br';

 //Other
 $bNumberShown = false;
 foreach(range('0','9') as $n){
   if($letter == $n) {
 printf('%snbsp',$n)
   }else{
 if ($bNumberShown){
   printf('a href=?letter=%s%s/anbsp;',$n,$n);
 }else{
   printf('a href=?letter=%s#%s/anbsp;',$n,$n);
   $bNumberShown = true;
 }
   }
 }
  echo /bbr/divp;

?

-- 

Bastien

Cat, the other other white meat

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Miller, Terion



On 7/31/09 12:43 PM, Bastien Koert phps...@gmail.com wrote:

On Fri, Jul 31, 2009 at 1:40 PM, Miller,
Teriontmil...@springfi.gannett.com wrote:



 On 7/31/09 12:27 PM, Bastien Koert phps...@gmail.com wrote:

 $letter = isset($_GET['letter']) ? $_GET['letter'] :;

  echo 'div align=centerb';

  foreach(range('A','Z') as $c){
   ($letter == $c) ? printf('%snbsp',$c) : printf('a
 href=browse.php?letter=%s%s/anbsp;',$c,$c);
  }

  echo 'br';

  //Other
  $bNumberShown = false;
  foreach(range('0','9') as $n){
   if($letter == $n) {
 printf('%snbsp',$n)
   }else{
if ($bNumberShown){
   printf('a href=?letter=%s%s/anbsp;',$n,$n);
 }else{
   printf('a href=?letter=%s#%s/anbsp;',$n,$n);
   $bNumberShown = true;
 }
  }

  echo /bbr/divp;

 Looks like it would work but I keep getting syntax error unexpected { at the 
 first
  }else{
 I have tried to move the brackets around but it just moves the error


My bad, missed a closing curly brace on the foreach loop

?php
 $letter = isset($_GET['letter']) ? $_GET['letter'] :;

 echo 'div align=centerb';

 foreach(range('A','Z') as $c){
   ($letter == $c) ? printf('%snbsp',$c) : printf('a
href=browse.php?letter=%s%s/anbsp;',$c,$c);
 }

 echo 'br';

 //Other
 $bNumberShown = false;
 foreach(range('0','9') as $n){
   if($letter == $n) {
 printf('%snbsp',$n)
   }else{
 if ($bNumberShown){
   printf('a href=?letter=%s%s/anbsp;',$n,$n);
 }else{
   printf('a href=?letter=%s#%s/anbsp;',$n,$n);
   $bNumberShown = true;
 }
   }
 }
  echo /bbr/divp;

?

--

Bastien

Cat, the other other white meat

Argh still nothing just the blank page of death...

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Shawn McKenzie
Miller, Terion wrote:
 
 
 On 7/31/09 12:43 PM, Bastien Koert phps...@gmail.com wrote:
 
 On Fri, Jul 31, 2009 at 1:40 PM, Miller,
 Teriontmil...@springfi.gannett.com wrote:


 On 7/31/09 12:27 PM, Bastien Koert phps...@gmail.com wrote:

 $letter = isset($_GET['letter']) ? $_GET['letter'] :;

  echo 'div align=centerb';

  foreach(range('A','Z') as $c){
   ($letter == $c) ? printf('%snbsp',$c) : printf('a
 href=browse.php?letter=%s%s/anbsp;',$c,$c);
  }

  echo 'br';

  //Other
  $bNumberShown = false;
  foreach(range('0','9') as $n){
   if($letter == $n) {
 printf('%snbsp',$n)
   }else{
if ($bNumberShown){
   printf('a href=?letter=%s%s/anbsp;',$n,$n);
 }else{
   printf('a href=?letter=%s#%s/anbsp;',$n,$n);
   $bNumberShown = true;
 }
  }

  echo /bbr/divp;

 Looks like it would work but I keep getting syntax error unexpected { at the 
 first
  }else{
 I have tried to move the brackets around but it just moves the error

 
 My bad, missed a closing curly brace on the foreach loop
 
 ?php
  $letter = isset($_GET['letter']) ? $_GET['letter'] :;
 
  echo 'div align=centerb';
 
  foreach(range('A','Z') as $c){
($letter == $c) ? printf('%snbsp',$c) : printf('a
 href=browse.php?letter=%s%s/anbsp;',$c,$c);
  }
 
  echo 'br';
 
  //Other
  $bNumberShown = false;
  foreach(range('0','9') as $n){
if($letter == $n) {
  printf('%snbsp',$n)
}else{
  if ($bNumberShown){
printf('a href=?letter=%s%s/anbsp;',$n,$n);
  }else{
printf('a href=?letter=%s#%s/anbsp;',$n,$n);
$bNumberShown = true;
  }
}
  }
   echo /bbr/divp;
 
 ?
 
 --
 
 Bastien
 
 Cat, the other other white meat
 
 Argh still nothing just the blank page of death...

Maybe you need a ; after printf('%snbsp',$n).

Also, maybe you need an editor with a syntax highlighter?  You and PJ
should get together and decide on one.

-- 
Thanks!
-Shawn
http://www.spidean.com

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Miller, Terion



--snip---

--
Well I almost have it with this, I keep getting an undefined index $letter 
error though and then it outputs the $menu how do I fix that

  //Create array with letters AND number sign  $letters 
= range('A','Z');  array_push($letters, '#');   
 $menu = '';  
foreach($letters as $letter) {  $menu .= ($letter 
== $_GET['letter'])? sprintf('%snbsp', 
$letter): sprintf('a 
href=browse.php?letter=%s%s/anbsp;', $letter, $letter);   
   }

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Bastien Koert
On Fri, Jul 31, 2009 at 2:51 PM, Miller,
Teriontmil...@springfi.gannett.com wrote:



 --snip---

 --
 Well I almost have it with this, I keep getting an undefined index $letter 
 error though and then it outputs the $menu how do I fix that

  //Create array with letters AND number sign                          
 $letters = range('A','Z');                          array_push($letters, 
 '#');                                                    $menu = '';          
                 foreach($letters as $letter) {                              
 $menu .= ($letter == $_GET['letter'])                                ? 
 sprintf('%snbsp', $letter)                                : sprintf('a 
 href=browse.php?letter=%s%s/anbsp;', $letter, $letter);                 
          }




What if you just add a

$letters = '';

at the top?

-- 

Bastien

Cat, the other other white meat

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Miller, Terion



On 7/31/09 1:56 PM, Bastien Koert phps...@gmail.com wrote:

$letters = '';

Nope still gives the same error:  Notice: Undefined index: letter

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Miller, Terion



On 7/31/09 2:00 PM, Miller, Terion tmil...@springfi.gannett.com wrote:




On 7/31/09 1:56 PM, Bastien Koert phps...@gmail.com wrote:

$letters = '';

Nope still gives the same error:  Notice: Undefined index: letter

Well getting closer with this but now my output menu is not a clickable link?

  $letter = 
isset($_GET['letter']) ? $_GET['letter'] :;   
 //Create array with letters AND number sign
   $letters = range('A','Z');   
   array_push($letters, '#');   
 $menu = '';  foreach($letters as $letter) {
  $menu .= ($letter)  ? 
sprintf('%s', $letter)  : sprintf('a 
href=browse.php?letter=%s%s/anbsp', $letter, $letter);
  }echo div 
align=\center\b{$menu}/bbr //div;

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Bastien Koert
On Fri, Jul 31, 2009 at 3:10 PM, Miller,
Teriontmil...@springfi.gannett.com wrote:



 On 7/31/09 2:00 PM, Miller, Terion tmil...@springfi.gannett.com wrote:




 On 7/31/09 1:56 PM, Bastien Koert phps...@gmail.com wrote:

 $letters = '';

 Nope still gives the same error:  Notice: Undefined index: letter

 Well getting closer with this but now my output menu is not a clickable link?

                                                      $letter = 
 isset($_GET['letter']) ? $_GET['letter'] :;                                 
                        //Create array with letters AND number sign            
                                        $letters = range('A','Z');             
              array_push($letters, '#');                                       
              $menu = '';                          foreach($letters as 
 $letter) {                              $menu .= ($letter)                    
           ? sprintf('%s', $letter)                              : sprintf('a 
 href=browse.php?letter=%s%s/anbsp', $letter, $letter);                  
         }                                                    echo div 
 align=\center\b{$menu}/bbr //div;



check the view source for the link to see what is happening to make it fail
-- 

Bastien

Cat, the other other white meat

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Miller, Terion



On 7/31/09 3:08 PM, Bastien Koert phps...@gmail.com wrote:

On Fri, Jul 31, 2009 at 3:10 PM, Miller,
Teriontmil...@springfi.gannett.com wrote:



 On 7/31/09 2:00 PM, Miller, Terion tmil...@springfi.gannett.com wrote:




 On 7/31/09 1:56 PM, Bastien Koert phps...@gmail.com wrote:

 $letters = '';

 Nope still gives the same error:  Notice: Undefined index: letter

 Well getting closer with this but now my output menu is not a clickable link?

  $letter = 
 isset($_GET['letter']) ? $_GET['letter'] :; 
//Create array with letters AND number sign
$letters = range('A','Z'); 
  array_push($letters, '#');   
  $menu = '';  foreach($letters as 
 $letter) {  $menu .= ($letter)
   ? sprintf('%s', $letter)  : sprintf('a 
 href=browse.php?letter=%s%s/anbsp', $letter, $letter);  
 }echo div 
 align=\center\b{$menu}/bbr //div;



check the view source for the link to see what is happening to make it fail
--

Bastien

Cat, the other other white meat


I finally got it working pretty much..next I just have to apply it to the query 
so that if the user clicks the # it will pull the records that begin with a 
number instead of letter from the db...
On the home stretch...

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] ForEach Range Problems

2009-07-31 Thread Miller, Terion



-snip---

So I'm almost almost there, but now when I click the # it shows me all records, 
is my foreach range not right?

 //Create array with letters AND number sign
$letters = range('A','Z');array_push($letters, '#');
$menu = '';
$selectedLetter = isset($_GET['letter']) ? $_GET['letter'] : null;  
  foreach($letters as $letter) {$menu .= 
($letter == $selectedLetter)  ? sprintf('%snbsp', 
$letter)  : sprintf('a 
href=browse.php?letter=%s%s/anbsp;', $letter, $letter);   
 }echo div align=\center\b{$menu}/bbr //div;  

  
//Show all restaurants that start with $letter  not between A and Z 
   $other = ctype_digit($letter);   
  foreach(range('0','9') as 
$other) $sql = SELECT 
DISTINCT ID, name, address FROM restaurants WHERE name LIKE '{$other}%' ;  
   $result = mysql_query($sql) 
or die(mysql_error());  
   while($row = 
mysql_fetch_assoc($result)){

$name = $row['name'];   
  printf(   
 'a 
href=view.php?ID=%sb%s/bbr /%sbr /br //a',   
 $row['ID'],
  $row['name'], 
   $row['address']  
  );

}   


   //Show all restaurants that 
start with $letter$sql 
= SELECT DISTINCT ID, name, address FROM restaurants WHERE name LIKE 
'{$selectedLetter}%';
$result = mysql_query($sql) or die(mysql_error());  

 while($row = mysql_fetch_assoc($result)){  

  $name = 
$row['name']; 
printf(
'a href=view.php?ID=%sb%s/bbr /%sbr /br //a',   
 $row['ID'],
  $row['name'], 
   $row['address']  
  );

}

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach and form submission.

2009-03-30 Thread Igor Escobar
Try this...
$_POST = array_map('stri_tags', $_POST);



Igor Escobar
systems analyst  interface designer
www . igorescobar . com



On Sat, Mar 28, 2009 at 6:21 PM, Angus Mann angusm...@pobox.com wrote:

 Thanks Ashley...that did the trick.
 After reading about the limitations of strip_tags I decided to just replace
 the bad bits as below...
 It still uses your foreach suggestion but replaces  and  with (
 and ) instead of stripping tags.

 I think I will extend the good and bad arrays to deal with magic quotes
 also !

 $bad = array('','lt;','#60;', '', 'gt;', '#62');
 $good = array('(', '(', '(', ')', ')', ')');
 foreach ($_POST as $key = $value) {
 $_POST[$key] = str_ireplace($bad, $good, $value);

 }





  I'd do something like this, so as to preserve the original post data
 array:

 $data = Array();
 foreach($_POST as $key = $value)
 {
   $data[$key] = strip_tags($value);
 }

 Note that strip_tags() will not be able to decently clean up messy code
 (i.e. code where the opening or closing tags themselves aren't formed
 properly)


 Ash
 www.ashleysheridan.co.uk




 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] foreach and form submission.

2009-03-30 Thread Jan G.B.
That would be correct. but two things I have to add:

* it's called bad style to re-write (override) predefined vars like
_POST, _GET, _SERVER ...
* using strip_tags() to clean user-input for safe output ist not O.K.!
use htmlspecialchars(), at least.

Regards,


2009/3/28 Virgilio Quilario virgilio.quila...@gmail.com:
 Hi all.

 I'm writing a script that accepts several different forms with different 
 content. Depending on what data is sent with the form the script will do one 
 or the other think.

 Before the form data is processed I'd like to scrub it of HTML tags.

 I can do this manually as below but the form may have dozens of items of 
 data so I'd like to automate it.

 $_POST['name'] = strip_tags($_POST['name']);
 $_POST['address'] = strip_tags($_POST['address']);
 $_POST['phone'] = strip_tags($_POST['phone']);

 I saw a few lines of code once that used foreach  on the $_POST array 
 elements and it did not seem to matter how many or what names the elements 
 had.

 Conceptually like this

 foreach ($_POST - element) {
    $_POST-element = strip_tags($_POST-element)
 }

 Any ideas please ?

 Thanks.


 here,

 foreach ($_POST as $key = $value) {
  $_POST[$key] = strip_tags($value);
 }

 good luck.

 virgil
 http://www.jampmark.com

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach and form submission.

2009-03-28 Thread Ashley Sheridan
On Sat, 2009-03-28 at 18:28 +1000, Angus Mann wrote:
 Hi all.
 
 I'm writing a script that accepts several different forms with different 
 content. Depending on what data is sent with the form the script will do one 
 or the other think.
 
 Before the form data is processed I'd like to scrub it of HTML tags.
 
 I can do this manually as below but the form may have dozens of items of data 
 so I'd like to automate it.
 
 $_POST['name'] = strip_tags($_POST['name']);
 $_POST['address'] = strip_tags($_POST['address']);
 $_POST['phone'] = strip_tags($_POST['phone']);
 
 I saw a few lines of code once that used foreach  on the $_POST array 
 elements and it did not seem to matter how many or what names the elements 
 had.
 
 Conceptually like this
 
 foreach ($_POST - element) {
 $_POST-element = strip_tags($_POST-element)
 }
 
 Any ideas please ?
 
 Thanks.
I'd do something like this, so as to preserve the original post data
array:

$data = Array();
foreach($_POST as $key = $value)
{
$data[$key] = strip_tags($value);
}

Note that strip_tags() will not be able to decently clean up messy code
(i.e. code where the opening or closing tags themselves aren't formed
properly)


Ash
www.ashleysheridan.co.uk


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach and form submission.

2009-03-28 Thread Virgilio Quilario
 Hi all.

 I'm writing a script that accepts several different forms with different 
 content. Depending on what data is sent with the form the script will do one 
 or the other think.

 Before the form data is processed I'd like to scrub it of HTML tags.

 I can do this manually as below but the form may have dozens of items of data 
 so I'd like to automate it.

 $_POST['name'] = strip_tags($_POST['name']);
 $_POST['address'] = strip_tags($_POST['address']);
 $_POST['phone'] = strip_tags($_POST['phone']);

 I saw a few lines of code once that used foreach  on the $_POST array 
 elements and it did not seem to matter how many or what names the elements 
 had.

 Conceptually like this

 foreach ($_POST - element) {
    $_POST-element = strip_tags($_POST-element)
 }

 Any ideas please ?

 Thanks.


here,

foreach ($_POST as $key = $value) {
  $_POST[$key] = strip_tags($value);
}

good luck.

virgil
http://www.jampmark.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach and form submission.

2009-03-28 Thread Angus Mann

Thanks Ashley...that did the trick.
After reading about the limitations of strip_tags I decided to just replace 
the bad bits as below...
It still uses your foreach suggestion but replaces  and  with ( 
and ) instead of stripping tags.


I think I will extend the good and bad arrays to deal with magic quotes also 
!


$bad = array('','lt;','#60;', '', 'gt;', '#62');
$good = array('(', '(', '(', ')', ')', ')');
foreach ($_POST as $key = $value) {
$_POST[$key] = str_ireplace($bad, $good, $value);
}






I'd do something like this, so as to preserve the original post data
array:

$data = Array();
foreach($_POST as $key = $value)
{
   $data[$key] = strip_tags($value);
}

Note that strip_tags() will not be able to decently clean up messy code
(i.e. code where the opening or closing tags themselves aren't formed
properly)


Ash
www.ashleysheridan.co.uk





--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach and destroying variables for memory saving

2008-12-10 Thread Per Jessen
Tim | iHostNZ wrote:

 Somewhere i also read that one can save a lot of memory by destroying
 variables. Is that done with unset, setting it to null or something
 similar? 

unset()

 So, i take there is no garbage collection in php? I've never 
 actually looked at the c source code of php. Maybe its time to
 actually do that. But it might be easier if someone can answer this
 from the top of their head.

There is no real need - most PHP code runs in apache with each request
being separately initated and terminated.  There's no underlying
runtime manager as such. 


/Per Jessen, Zürich


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach and destroying variables for memory saving

2008-12-10 Thread ceo

PHP does have garbage_collection, and it's crucial in long-running CLI scripts.



Per is right, though, in that if your web-page Apache PHP script needs GC, you 
are doing something terribly wrong.



It is not as aggressive/thorough as, say, the Lisp GC, but it's there.



ymmv



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach question

2008-07-29 Thread Daniel Brown
On Tue, Jul 29, 2008 at 3:25 PM, Jason Pruim [EMAIL PROTECTED] wrote:

 function random($random){

$randomQuery = SELECT * FROM `current` ORDER BY Rand() LIMIT 2;

$result = mysql_query($randomQuery);
 $row[] = $result;


 foreach($row as $key = $value) {
 $random[$key] = $value;

 }

 return $random;

 }//End of function


 ?

You're missing mysql_fetch_array(), mysql_fetch_assoc(), or
something of the like.

Example:

?php
//  code

 $result = mysql_query($randomQuery);
 $row = mysql_fetch_array($result);

 foreach($row as $k = $v) {
 $random[$k] = $v;
 }

//  code
}
?

-- 
/Daniel P. Brown
Better prices on dedicated servers:
Intel 2.4GHz/60GB/512MB/2TB $49.99/mo.
Intel 3.06GHz/80GB/1GB/2TB $59.99/mo.
Dedicated servers, VPS, and hosting from $2.50/mo.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach question

2008-07-29 Thread Micah Gersten
You cannot do this:
$row[] = $result;   

You need to loop around this:
$row = mysql_fetch_assoc($result);

Thank you,
Micah Gersten
onShore Networks
Internal Developer
http://www.onshore.com



Jason Pruim wrote:
 Hey Everyone...

 So I am attempting to pull 2 random records from a MySQL database, so
 I wrote a function which I'll paste below. I had it mostly working
 with a while() statement, but I wanted to try a foreach to see if I
 could get the formatting a little bit better.

 Basically... What it does is grab 2 records at random from the
 database, and display the images. What I want is something that looks
 like this: img1 VS img2

 right now though... I'm at a lose to figure out why it's not returning
 any records but not throwing any errors... Any ideas what I'm missing?

 ?PHP
 //function for pulling random pictures from the database


 function random($random){
 
 $randomQuery = SELECT * FROM `current` ORDER BY Rand() LIMIT 2;

 $result = mysql_query($randomQuery);
 $row[] = $result;   


 foreach($row as $key = $value) {
 $random[$key] = $value;

 }

 return $random;

 }//End of function


 ?

 Any ideas?




-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach question

2008-07-29 Thread Jason Pruim


On Jul 29, 2008, at 3:33 PM, Daniel Brown wrote:

On Tue, Jul 29, 2008 at 3:25 PM, Jason Pruim [EMAIL PROTECTED]  
wrote:


function random($random){

  $randomQuery = SELECT * FROM `current` ORDER BY Rand() LIMIT  
2;


  $result = mysql_query($randomQuery);
$row[] = $result;


foreach($row as $key = $value) {
$random[$key] = $value;

}

return $random;

}//End of function


?


   You're missing mysql_fetch_array(), mysql_fetch_assoc(), or
something of the like.

   Example:

?php
//  code

$result = mysql_query($randomQuery);
$row = mysql_fetch_array($result);

foreach($row as $k = $v) {
$random[$k] = $v;
}

//  code
}
?




Added that, then changed how I was calling it and it works great  
now... Thanks for looking... The problem was definitely between the  
chair and the keyboard on this one.





--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach loop to set variables

2008-04-25 Thread Stut

On 25 Apr 2008, at 14:12, jamest wrote:
I am passing an array to a class which I want to take the array data  
and

create some variables from the array's keys and values.

So I want to create (in this case 21) new variables that I want to  
create in

the foreach but with no success.

foreach ($formdata as $key = $value) {
$key = $value;
}


$$key = $value;

They're called variable variables - search the manual for that term  
for more info.



But this doesn't work. The variables aren't set.

I was thinking that I could set up the variables outside of the  
function by
using public $variablename for all the different variables then set  
the

variable value using:

foreach ($formdata as $key = $value) {
$this-key = $value;
}


$this-$key = $value;

-Stut

--
http://stut.net/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach loop to set variables

2008-04-25 Thread Jason Norwood-Young

On Fri, 2008-04-25 at 06:12 -0700, jamest wrote:
 I am passing an array to a class which I want to take the array data and
 create some variables from the array's keys and values.
 
 So I want to create (in this case 21) new variables that I want to create in
 the foreach but with no success.
 
 foreach ($formdata as $key = $value) {
   echo $key = $value;
 }
 
 This echo's all the data how I would expect.  But taking the echo out to
 have:
 
 foreach ($formdata as $key = $value) {
   $key = $value;
 }
 
 But this doesn't work. The variables aren't set.
 
 I was thinking that I could set up the variables outside of the function by
 using public $variablename for all the different variables then set the
 variable value using:
 
 foreach ($formdata as $key = $value) {
   $this-key = $value;
 }

How about $this-formdata?


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach loop to set variables

2008-04-25 Thread Casey

On Apr 25, 2008, at 6:12 AM, jamest [EMAIL PROTECTED] wrote:



I am passing an array to a class which I want to take the array data  
and

create some variables from the array's keys and values.

So I want to create (in this case 21) new variables that I want to  
create in

the foreach but with no success.

foreach ($formdata as $key = $value) {
   echo $key = $value;
}

This echo's all the data how I would expect.  But taking the echo  
out to

have:

foreach ($formdata as $key = $value) {
   $key = $value;
}

But this doesn't work. The variables aren't set.

I was thinking that I could set up the variables outside of the  
function by
using public $variablename for all the different variables then set  
the

variable value using:

foreach ($formdata as $key = $value) {
   $this-key = $value;
}

But that didn't work either.
--
View this message in context: 
http://www.nabble.com/foreach-loop-to-set-variables-tp16895552p16895552.html
Sent from the PHP - General mailing list archive at Nabble.com.


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



foreach ($formdata as $key = $value)
$formdata[$key] = $value;

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach loop to set variables

2008-04-25 Thread jamest

Thats perfect.  I didn't even know about this.

Stut wrote:
 
 
 $$key = $value;
 
 They're called variable variables - search the manual for that term  
 for more info.
 
 -Stut
 
 -- 
 http://stut.net/
 
 

-- 
View this message in context: 
http://www.nabble.com/foreach-loop-to-set-variables-tp16895552p16898164.html
Sent from the PHP - General mailing list archive at Nabble.com.


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] foreach loop to set variables

2008-04-25 Thread Jim Lucas

jamest wrote:

I am passing an array to a class which I want to take the array data and
create some variables from the array's keys and values.

So I want to create (in this case 21) new variables that I want to create in
the foreach but with no success.

foreach ($formdata as $key = $value) {
echo $key = $value;
}

This echo's all the data how I would expect.  But taking the echo out to
have:

foreach ($formdata as $key = $value) {
$key = $value;
}

But this doesn't work. The variables aren't set.

I was thinking that I could set up the variables outside of the function by
using public $variablename for all the different variables then set the
variable value using:

foreach ($formdata as $key = $value) {
$this-key = $value;
}

But that didn't work either.


But wait, PHP has a function to do this already.

Wait for it...

Wait for it...

Wait for it...

Wait for it...


extract()  that's it!!!

--
Jim Lucas

   Some men are born to greatness, some achieve greatness,
   and some have greatness thrust upon them.

Twelfth Night, Act II, Scene V
by William Shakespeare


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach

2008-01-27 Thread Nathan Nobbe
On Jan 23, 2008 8:02 AM, Eric Butera [EMAIL PROTECTED] wrote:

 Maybe someday SPL will become part of the PHP manual too. ;)


ill admit, the doxygen documentation is a little daunting at first.  at
least
more so than phpDocumentor for example.  but once youve cruised around
the spl docs for a little while, you can see its truly amazing.  marcus has
done a superb job with it!
and, ive made a discovery.  im sure this is novice level, for people who
actually
have a clue what they are doing w/ spl, which unfortunately seems like next
to
no one.   well, im getting to know it; anyway, i digress.
DualIterator is not 'in' php, because well, its not written in c.  marcus
has distributed
several classes and procedural files along with the c code to round out the
spl
extension.  the example code is included in the php source, so in order to
use it
youll have to download the source and unpack it.  you will find the example
code
beneath
ext/spl/examples
in particular, the DualIterator class is in the
dualiterator.inc
file.  and now, for my last trick, an example of the DualIterator, to
illustrate how simple
it is, (and incidentally less error prone than rolling your own, since its
been tested).

?php
require('dualiterator.inc');

 $leftSideArray = array('one' = 1, 'two' = 2, 'three' = 3, 'four' = 4);
 $rightSideArray = array('one' = 'a', 'two' = 'b', 'three' = 'c', 'four'
= 'd');

 $di = new DualIterator(new ArrayIterator($leftSideArray), new
ArrayIterator($rightSideArray));

while($di-valid()) {
var_dump($di-key());
var_dump($di-current());
$di-next();
}
?

to test whether the arrays have the same number of keys and values; in this
example all we
would have to do is:
$di-areEqual();

-nathan


Re: [PHP] Foreach

2008-01-27 Thread Eric Butera
On Jan 27, 2008 1:33 PM, Nathan Nobbe [EMAIL PROTECTED] wrote:
 On Jan 23, 2008 8:02 AM, Eric Butera [EMAIL PROTECTED] wrote:

  Maybe someday SPL will become part of the PHP manual too. ;)
 

 ill admit, the doxygen documentation is a little daunting at first.  at
 least
 more so than phpDocumentor for example.  but once youve cruised around
  the spl docs for a little while, you can see its truly amazing.  marcus has
 done a superb job with it!
 and, ive made a discovery.  im sure this is novice level, for people who
 actually
 have a clue what they are doing w/ spl, which unfortunately seems like next
 to
  no one.   well, im getting to know it; anyway, i digress.
 DualIterator is not 'in' php, because well, its not written in c.  marcus
 has distributed
 several classes and procedural files along with the c code to round out the
 spl
  extension.  the example code is included in the php source, so in order to
 use it
 youll have to download the source and unpack it.  you will find the example
 code
 beneath
 ext/spl/examples
  in particular, the DualIterator class is in the
 dualiterator.inc
 file.  and now, for my last trick, an example of the DualIterator, to
 illustrate how simple
 it is, (and incidentally less error prone than rolling your own, since its
 been tested).

 ?php
 require('dualiterator.inc');

  $leftSideArray = array('one' = 1, 'two' = 2, 'three' = 3, 'four' = 4);
  $rightSideArray = array('one' = 'a', 'two' = 'b', 'three' = 'c', 'four'
 = 'd');

  $di = new DualIterator(new ArrayIterator($leftSideArray), new
 ArrayIterator($rightSideArray));

 while($di-valid()) {
 var_dump($di-key());
 var_dump($di-current());
 $di-next();
  }
 ?

 to test whether the arrays have the same number of keys and values; in this
 example all we
 would have to do is:
 $di-areEqual();

 -nathan


I was just pointing out how fragmented PHP5+ is.  Look at the docs on
SPL and the DOM stuff, it's horrible.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach

2008-01-27 Thread Nathan Nobbe
On Jan 27, 2008 7:24 PM, Eric Butera [EMAIL PROTECTED] wrote:

 I was just pointing out how fragmented PHP5+ is.  Look at the docs on
 SPL and the DOM stuff, it's horrible.


i hear you, and i agree, most of the php docs are good, but some of the
oop stuff is kinda weak, like SoapClient, and DateTime for example.  In
this regard i think the SPL docs are pretty kick-ass.  although isolated,
they are in themselves quite robust and complete.
but really, after saying DualIterator would be perfect for this case, i had
to post an example ;)

-nathan


Re: [PHP] Foreach

2008-01-23 Thread Eric Butera
On Jan 23, 2008 12:58 AM, Nathan Nobbe [EMAIL PROTECTED] wrote:
 On Jan 18, 2008 5:24 PM, Richard Lynch [EMAIL PROTECTED] wrote:

  If you are trying to keep the names and orders in parallel you need
  to do something not unlike:
 
  while (list($key, $name) = each($names)){
   $order = $orders[$key];
   $query = update whatever set order = $order where name = '$name';
  }


 just as a mention; spl has a DualIterator class that would be perfect for
 this
 situation.  i hesitate to mention it though, since ive not found it in any
 php
 version.  its there in the doc, but not in actual php; what a shame.
 http://www.php.net/~helly/php/ext/spl/classDualIterator.html

 i can only expect well see it in a subsequent version; that there is a
 reason
 its not yet made it..

 -nathan


Maybe someday SPL will become part of the PHP manual too. ;)

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach

2008-01-22 Thread Nathan Nobbe
On Jan 18, 2008 5:24 PM, Richard Lynch [EMAIL PROTECTED] wrote:

 If you are trying to keep the names and orders in parallel you need
 to do something not unlike:

 while (list($key, $name) = each($names)){
  $order = $orders[$key];
  $query = update whatever set order = $order where name = '$name';
 }


just as a mention; spl has a DualIterator class that would be perfect for
this
situation.  i hesitate to mention it though, since ive not found it in any
php
version.  its there in the doc, but not in actual php; what a shame.
http://www.php.net/~helly/php/ext/spl/classDualIterator.html

i can only expect well see it in a subsequent version; that there is a
reason
its not yet made it..

-nathan


Re: [PHP] Foreach

2008-01-18 Thread mike
On 1/18/08, Eric Butera [EMAIL PROTECTED] wrote:

 Nonetheless as I keep re-iterating, people will copy and paste this
 stuff as is because they don't know better.  It is the responsibility
 of people writing the answers to make sure their code is validated and
 as secure as possible unless there is some glaringly obvious comment
 saying {get your data here} with a link to how to validate it
 properly.

I agree. Everyone should be pushing for the best code possible here...

 Using session based form tokens is a better approach to make sure the
 post came from within your application.

Except if your sessions timeout while the user is filling out the
form. I have a forum and sometimes people spend a LOT of time
composing messages (copy/pasting replies to reply to them, etc) and if
it's session-based, their session may timeout (depending on how it's
configured) before they hit submit, resulting in a total loss of data.
Unless the application understands to restart a session, but then
what's the point of the token...

I have non-user-specific tokens issued every request (with an expiry
of 24 hours) per form so it can only be submitted once. It's worked
pretty well, but as with everything there are a couple ways around it,
but it would take some work to do that.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach

2008-01-18 Thread Eric Butera
On Jan 18, 2008 5:06 PM, mike [EMAIL PROTECTED] wrote:
 On 1/18/08, Eric Butera [EMAIL PROTECTED] wrote:

  Nonetheless as I keep re-iterating, people will copy and paste this
  stuff as is because they don't know better.  It is the responsibility
  of people writing the answers to make sure their code is validated and
  as secure as possible unless there is some glaringly obvious comment
  saying {get your data here} with a link to how to validate it
  properly.

 I agree. Everyone should be pushing for the best code possible here...

  Using session based form tokens is a better approach to make sure the
  post came from within your application.

 Except if your sessions timeout while the user is filling out the
 form. I have a forum and sometimes people spend a LOT of time
 composing messages (copy/pasting replies to reply to them, etc) and if
 it's session-based, their session may timeout (depending on how it's
 configured) before they hit submit, resulting in a total loss of data.
 Unless the application understands to restart a session, but then
 what's the point of the token...

 I have non-user-specific tokens issued every request (with an expiry
 of 24 hours) per form so it can only be submitted once. It's worked
 pretty well, but as with everything there are a couple ways around it,
 but it would take some work to do that.


That is a good point to consider.  On our servers we have the session
timeout set to when the browser is closed so I forget sometimes people
put actual time limits on them.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach

2008-01-18 Thread Pastor Steve
Yes, each variable is an array. foreach works individually with no problems.
The problem I am having is getting both to update the table in MySQL. It
will update  $i three times with no problem, however, it will only update $t
with the last value in the array.

Name is a checkbox and contains the name of the record from the db. Order is
a select menu with a number. (which is the number drawn from the number of
records in the db). I would like to see both values come across and update
the table however many times necessary. Name would update the name and order
would update order. Order is the order in which each record will appear on
the page.

I hope this makes more sense. I wish I knew more, and then I would be able
to formulate my questions better. Thank you so much for your help.

Steve M.

on 1/17/08 10:07 PM David Giragosian ([EMAIL PROTECTED]) wrote:

 On 1/17/08, mike [EMAIL PROTECTED] wrote:
 On 1/17/08, Nathan Nobbe  [EMAIL PROTECTED]
 mailto:[EMAIL PROTECTED]  wrote:
 
  $name = $_POST['name'];
  if ($name) {
  foreach ($name as $t) {
 
echo $t;
} 
 
$order = $_POST['order'];
if ($order) {
foreach ($order as $i) {
 
 
 there are a few different issues here; first of all; are you sure
 $_POST['name'] 
 and $_POST['order'] are even arrays?
 
 hint:
 
 if(isset($_POST['name'])  is_array($_POST['name']))
 
 Steve,  
 
 // Do you have several html form elements such as input type=text
 name=name[] in your html?
 // Mike's suggestion...
 if( isset( $_POST['name'] )  is_array( $_POST['name'] ) ) {
 
 // you'll never get in here if you don't...
 $name = $_POST['name'];
  
// foreach expects an array, as Nathan states. Even if $name is an
 array, $t 
// will hold only the last value in the array when the foreach loop is
 exited
// because $t is being overwritten with each iteration.
foreach ($name as $t) {
 
echo $t;
 
} // end foreach ($name)
 
$order = $_POST['order'];

if ($order) {

// see above about arrays and foreach
foreach ($order as $i) {
 
   //Update the table in MySQL
 
   $i = mysql_real_escape_string($i, $cnx); // One of
 Eric's suggestions
 
   $update_data = UPDATE sections SET `order` = '$i' WHERE
 name = '$t';
 
   $response = mysql_query( $update_data, $cnx );
 
   if(mysql_error()) die ('database errorbr'.
 mysql_error());
 
   echo $i;
 
} //end foreach ($order)
 
}
 
 }
 
 Assuming both $_POST['name'] and $_POST['order'] are arrays, the way your code
 is now structured, the table `sections` will have the record(s) where name
 equals the last value in the $names array updated multiple times, once for
 each value in the $order array, but all you will see is that the record(s)
 will have the last value in the $order array.
 
 See if this makes any sense and then ask more questions.
 
 David
 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Foreach

2008-01-18 Thread Andrés Robinet
 -Original Message-
 From: Eric Butera [mailto:[EMAIL PROTECTED]
 Sent: Friday, January 18, 2008 11:21 PM
 To: mike
 Cc: PHP eMail List
 Subject: Re: [PHP] Foreach
 
 On Jan 18, 2008 5:06 PM, mike [EMAIL PROTECTED] wrote:
  On 1/18/08, Eric Butera [EMAIL PROTECTED] wrote:
 
   Nonetheless as I keep re-iterating, people will copy and paste this
   stuff as is because they don't know better.  It is the
 responsibility
   of people writing the answers to make sure their code is validated
 and
   as secure as possible unless there is some glaringly obvious
 comment
   saying {get your data here} with a link to how to validate it
   properly.
 
  I agree. Everyone should be pushing for the best code possible
 here...
 
   Using session based form tokens is a better approach to make sure
 the
   post came from within your application.
 
  Except if your sessions timeout while the user is filling out the
  form. I have a forum and sometimes people spend a LOT of time
  composing messages (copy/pasting replies to reply to them, etc) and
 if
  it's session-based, their session may timeout (depending on how it's
  configured) before they hit submit, resulting in a total loss of
 data.
  Unless the application understands to restart a session, but then
  what's the point of the token...
 
  I have non-user-specific tokens issued every request (with an expiry
  of 24 hours) per form so it can only be submitted once. It's worked
  pretty well, but as with everything there are a couple ways around
 it,
  but it would take some work to do that.
 
 
 That is a good point to consider.  On our servers we have the session
 timeout set to when the browser is closed so I forget sometimes people
 put actual time limits on them.
 
 --

Please, don't get me wrong, I'm just curious, how does the server know when
the browser is closed? Do you use javascript (AJAX) or something to notify
the server?
As far as I remember, sessions are:

1 - A cookie (or a GET/POST parameter that gets passed by from page to page)
2 - A session file

So when the user closes the browser and opens it up again, a new cookie will
be generated by the server if it didn't get one in the request (and a new
session file will be created as well), but that doesn't delete the old
session file. I mean, isn't it supposed to be a garbage collection feature
in any session implementation (that is what the session timeout is for,
isn't it)? Or is it just that I'm missing something?

Regards,

Rob

PS. Yes, I know you can have persistent cookies, and you can store session
data in there. But the data length has a limit of some KB AFAIK, and you'd
have to encrypt/decrypt sensitive information.


Andrés Robinet | Lead Developer | BESTPLACE CORPORATION
5100 Bayview Drive 206, Royal Lauderdale Landings, Fort Lauderdale, FL 33308
| TEL 954-607-4207 | FAX 954-337-2695
Email: [EMAIL PROTECTED]  | MSN Chat: [EMAIL PROTECTED]  |  SKYPE:
bestplace |  Web: http://www.bestplace.biz | Web: http://www.seo-diy.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach

2008-01-18 Thread Richard Lynch
If you are trying to keep the names and orders in parallel you need
to do something not unlike:

while (list($key, $name) = each($names)){
  $order = $orders[$key];
  $query = update whatever set order = $order where name = '$name';
}

This completely ignores security and error checking in the name of
simplicity, which means it's missing about 20 more lines of code to
make it safe...

On Fri, January 18, 2008 10:17 am, Pastor Steve wrote:
 Yes, each variable is an array. foreach works individually with no
 problems.
 The problem I am having is getting both to update the table in MySQL.
 It
 will update  $i three times with no problem, however, it will only
 update $t
 with the last value in the array.

 Name is a checkbox and contains the name of the record from the db.
 Order is
 a select menu with a number. (which is the number drawn from the
 number of
 records in the db). I would like to see both values come across and
 update
 the table however many times necessary. Name would update the name and
 order
 would update order. Order is the order in which each record will
 appear on
 the page.

 I hope this makes more sense. I wish I knew more, and then I would be
 able
 to formulate my questions better. Thank you so much for your help.

 Steve M.

 on 1/17/08 10:07 PM David Giragosian ([EMAIL PROTECTED]) wrote:

 On 1/17/08, mike [EMAIL PROTECTED] wrote:
 On 1/17/08, Nathan Nobbe  [EMAIL PROTECTED]
 mailto:[EMAIL PROTECTED]  wrote:

  $name = $_POST['name'];
  if ($name) {
  foreach ($name as $t) {

echo $t;
}

$order = $_POST['order'];
if ($order) {
foreach ($order as $i) {


 there are a few different issues here; first of all; are you sure
 $_POST['name']
 and $_POST['order'] are even arrays?

 hint:

 if(isset($_POST['name'])  is_array($_POST['name']))

 Steve,

 // Do you have several html form elements such as input type=text
 name=name[] in your html?
 // Mike's suggestion...
 if( isset( $_POST['name'] )  is_array( $_POST['name'] ) ) {

 // you'll never get in here if you don't...
 $name = $_POST['name'];

// foreach expects an array, as Nathan states. Even if $name
 is an
 array, $t
// will hold only the last value in the array when the
 foreach loop is
 exited
// because $t is being overwritten with each iteration.
foreach ($name as $t) {

echo $t;

} // end foreach ($name)

$order = $_POST['order'];

if ($order) {

// see above about arrays and foreach
foreach ($order as $i) {

   //Update the table in MySQL

   $i = mysql_real_escape_string($i, $cnx); //
 One of
 Eric's suggestions

   $update_data = UPDATE sections SET `order` =
 '$i' WHERE
 name = '$t';

   $response = mysql_query( $update_data, $cnx );

   if(mysql_error()) die ('database errorbr'.
 mysql_error());

   echo $i;

} //end foreach ($order)

}

 }

 Assuming both $_POST['name'] and $_POST['order'] are arrays, the way
 your code
 is now structured, the table `sections` will have the record(s)
 where name
 equals the last value in the $names array updated multiple times,
 once for
 each value in the $order array, but all you will see is that the
 record(s)
 will have the last value in the $order array.

 See if this makes any sense and then ask more questions.

 David


 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




-- 
Some people have a gift link here.
Know what I want?
I want you to buy a CD from some indie artist.
http://cdbaby.com/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach

2008-01-18 Thread Wolf
Steve,

This should work as some basic sudo code.  You are running into a number of 
issues with your usage of the foreach as it sounds like what you really want to 
do is walk through one array and grab the corresponding value from another.

?php
// First check to make sure you are getting both fields
if(isset($_POST['name'])  is_array($_POST['name'])  isset($_POST['order']) 
 is_array($_POST['order']))
{
 // Now assign them to easier to play with variables
 $names=$_POST['name'];
 $orders=$_POST['orders'];
 // This tests for the same number of items as names
 if (count($names) == count($orders)) 
 { 
  $i=0;
  while($i=count($names))
  {
   $update_data = UPDATE sections SET `order` = '$orders[$i]' WHERE name = 
'$names[$i]';
   $response = mysql_query( $update_data, $cnx );
   if(mysql_error()) die ('database errorbr'.mysql_error());
  }
 }
}
?

HTH,
Wolf

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Foreach

2008-01-18 Thread Eric Butera
On Jan 18, 2008 11:38 AM, Wolf [EMAIL PROTECTED] wrote:
 Steve,

 This should work as some basic sudo code.  You are running into a number of 
 issues with your usage of the foreach as it sounds like what you really want 
 to do is walk through one array and grab the corresponding value from another.

 ?php
 // First check to make sure you are getting both fields
 if(isset($_POST['name'])  is_array($_POST['name'])  
 isset($_POST['order'])  is_array($_POST['order']))
 {
  // Now assign them to easier to play with variables
  $names=$_POST['name'];
  $orders=$_POST['orders'];
  // This tests for the same number of items as names
  if (count($names) == count($orders))
  {
   $i=0;
   while($i=count($names))
   {
$update_data = UPDATE sections SET `order` = '$orders[$i]' WHERE name = 
 '$names[$i]';
$response = mysql_query( $update_data, $cnx );
if(mysql_error()) die ('database errorbr'.mysql_error());
   }
  }
 }
 ?

 HTH,
 Wolf


 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php



Hi Wolf,

Your code is missing data validation!  Hopefully you don't do stuff
like that either.

function super_duper_escaper($value, $db) {
if (!get_magic_quotes_gpc()) {
$value = mysql_real_escape_string($value, $db);
}
return $value;
}

$_sql = UPDATE sections SET `order` = %d WHERE name = '%s';
$sql = sprintf(
$_sql,
(int)$orders[$i],
super_duper_escaper($names[$i], $cnx)
);

What we're doing here is making sure that the order is a number and
that the name is a string that properly escapes out the quotes to make
sure people can't break out of the context of data and into commands.
Look up SQL injection for more information.

Don't rely on magic quotes, etc as it is a server specific setting, is
going away in php6, and does not take character sets into
consideration.  The mysql extension is just as bad as it wont allow
you to update the character set context from the mysql server default.
 So use mysqli or pdo unless everything matches across the board.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



  1   2   3   >