Page 1 of 1

Returning last value in loop

Posted: Wed Jul 16, 2008 6:46 pm
by Addos
I have a table in the database with a column with the following values
v_number
12345
54321
789

When I loop through this with the code below using the from field it seems to just return the last value 789 as ‘is valid’ but not the others.

Why is this not returning ‘Valid’ when I submit the other correct values?

I know there are security issues with this from but I’m just working on the basics to get this working before adding the security.

Thanks

Code: Select all

// run loop to see if submitted voucher exists.
if ($_POST && array_key_exists('MM_update',$_POST)) {
 
 do { 
    if (isset($_POST['v_number_1']) && ($_POST['v_number_1']) == $row_GetVouchers['v_number']) {
// if it does not exist then point that out
$number = 'is  valid ';
        }else{
      
    $number = '<strong> Not valid </strong>';
     }
            } while ($row_GetVouchers = mysql_fetch_assoc($GetVouchers));
}
 
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
 
      Voucher 1:
          <?php if (isset($number) && !empty($number)) {
          echo $number ; }  ?> 
      
      <input type="text" name="v_number_1" value="<?php if (isset($_POST['v_number_1'])) echo $_POST['v_number_1'];?>" size="32">
      <input type="submit" value="Apply Vouchers">
  <input type="hidden" name="MM_update" value="form1">
 
</form>

Re: Returning last value in loop

Posted: Wed Jul 16, 2008 8:12 pm
by Stryks
Wow ... a lot to comment on. I'll keep it to the question you asked though.

Basically, your do ... while loop overrides the value of $number with each pass. So the first pass might get set to valid, but because the second value returned doesnt match, it gets overwritten to 'not valid'.

If you really want to keep this format, you could just say ...

Code: Select all

if($number !=== ' is valid') $number = '<strong> Not valid </strong>';
But I guess the more direct question would be, why aren't you just checking to see if the voucher number specified exists instead of returning a list of valid vouchers and looping through them?

There could possibly be a reason for pulling all vouchers, though I can't think of one. But perhaps a cleaner way would be, say ...

Code: Select all

 
if (isset($_POST['v_number_1'])) {
   $number = '<strong> Not valid </strong>';
   while($row_GetVouchers = mysql_fetch_assoc($GetVouchers))
      if($_POST['v_number_1'] == $row_GetVouchers['v_number']) $number = ' is valid';
   }
}
 
That's untested of course, but you get the drift. It gets set to not found by default, and updated to found if it turns up. Also, you include as little as possible in the loop to help keep the code optimized.

But I really would just set up a where clause on the query and just return vouchers that have the correct voucher number. If you get a result, then it exists, otherwise it doesn't. Easy.

Hope this helps.