doujia2386 2013-06-26 22:13
浏览 63
已采纳

foreach循环复制第一行

This is the code that I have

<?php
$checkbox = $_REQUEST['checkbox']; 
for($i=0; $i<count($_REQUEST['checkbox']); $i++){ 
    $del_id = $checkbox[$i]; 
    $get_info=$db->prepare("SELECT * FROM `pending_payments` WHERE `id` = ?");
    $get_info->bind_param('i', $del_id);
    $get_info->execute();
    $result = $get_info->get_result();
    $info[] = $result->fetch_assoc();
    foreach($info as $row){ 
        $amount = $row['amount'];
        $email = $row['email'];
        echo"
        <input type='text' style='height: 35px;' name='Amount[]' value='".$amount."' />
        <input type='text' style='height: 35px;' name='EmailAddress[]' value='".$email."' /><br />
        ";
    }
}
?>

The problem that I am having is that it is duplicating the first row it finds. I have 2 entries into the database, and it is repeating the first row twice before going on the the third, when I print_r $info it gives me this

Array ( [0] => Array ( [id] => 1 [username] => ccarson030308 [amount] => 5.00 [processor] => PayPal [email] => ccarson030308@gmail.com [submitted_date] => 1372030166 ) )

then shows the echo for that line then starts over and shows

Array ( [0] => Array ( [id] => 1 [username] => ccarson030308 [amount] => 5.00 [processor] => PayPal [email] => ccarson030308@gmail.com [submitted_date] => 1372030166 ) [1] => Array ( [id] => 2 [username] => tatsu91 [amount] => 5.00 [processor] => PayPal [email] => sheynever@yahoo.com [submitted_date] => 1372030166 ) ) 

which should be the only thing it shows to begin with, do I have something wrong in my for loop? I don't normally loop for and foreach but it seemed to be the best method for what I am trying to do, but I am failing somehow.

Without adding the append [] I get 12 errors of Warning: Illegal string offset 'amount' Warning: Illegal string offset 'email'

  • 写回答

1条回答 默认 最新

  • duanbimo7212 2013-06-26 22:16
    关注

    Your code appends to $info for every query made. So when doing foreach($info ...) you will see output for the results produced in this iteration and for all the previous results.

    The output will therefore look like this:

    -------------- $i = 0
    Output from #1
    -------------- $i = 1
    Output from #1
    Output from #2
    -------------- $i = 2
    Output from #1
    Output from #2
    Output from #3
    -------------- etc
    

    You probably meant to write

    $info = $result->fetch_assoc(); // direct assignment, no append
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化