dongpiao1983 2017-04-13 06:03
浏览 28
已采纳

将从数据库中检索的行存储为php中的单独变量

I have a loop which displays the wanted rows but I also want each row to be stored in its own variable in php. I have a table that has an ID and an info column.

This displays the wanted ID and info:

if ($info = $stmnt2->fetch()) { 
do {
echo "$info[id] . $info[info] </br> "; 
   } while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}

I want each row to have its own variable so I can manipulate the data later down the line. Like the first row will be stored in a php variable called $one and the second row in $second. How can I do this?

  • 写回答

4条回答 默认 最新

  • duandu8202 2017-04-13 06:08
    关注

    I wouldn't use a variable to solve this! Take an array instead:

    $rows = [];
    
    if ($info = $stmnt2->fetch()) { 
        do {
            $rows[] = $info;
            echo $info['id'].$info['info']."</br>"; 
        } while ($info = $stmnt2->fetch());
    } else {
        echo "<p>No Info</p>";
    }
    
    if (!empty($rows)) {
    
        //you can change the values of the rows like the following.
        $rows[0]['id'] = 1; // The ID of the first row!
        $rows[0]['info'] = 'Some Info'; // The info of the first row!
        $rows[1]['id'] = 2; // The ID of the second row!
        $rows[1]['info'] = 'Some Info'; // The info of the second row!
        //...
    }
    

    With the above example each item on rows is one row ($rows[number_of_row - 1]).

    Hint: $info[id] and $info[info] isn't valid. You have to replace these with $info['id'] and $info['info']!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部