dongpiao1983 2017-04-13 14: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 14: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条)

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库