dongrong8972 2014-12-17 12:35
浏览 72
已采纳

将查询中的数据插入到数组中

I have a form where I have individual textboxes on-screen where I want to insert a pupil name into each one. Each textbox will contain one pupil name. I have an SQL query that gets all the pupils I want for the class this form is created for. When the SQL is run in PHPMyAdmin, the query returns the exact values I want.

The code below is what I had hoped would be to get the data from the database and put it into an array so that I could put each row into a textbox later. However when I run this code, the finished array only contains 1 element and is the second row found by the query. The records found by query are;

+--------------------------+
| Pupil_Name (Column name) |
+--------------------------+
| Sam Price                |
| Keith mcgareth           |
+--------------------------+

Only Keith mcrgareth is echoed at the end. When both records should be echoed.

$pupilarray = array();
$pupilquery = mysqli_query($connection, "SELECT Pupil_Name FROM tbllogin WHERE Class_Name = 'Heulog'         AND Access_Level = 'pupil'");
while($row = mysqli_fetch_assoc($pupilquery)){
$pupilarray = $row['Pupil_Name'];
}
echo $pupilarray;

Have I created my array wrong? or am I missing something?

  • 写回答

4条回答 默认 最新

  • dongxian2863 2014-12-17 12:36
    关注

    Since you put the echo right after the loop, you'll only get the last value. Put the echo inside if you want it to be printed as the loop goes on:

    while($row = mysqli_fetch_assoc($pupilquery)){
        $pupilarray = $row['Pupil_Name'];
        echo $pupilarray . '<br/>';
    }
    

    But if your intent is to create an array, then you should push it with the array notation on the assignment:

    $pupilarray = array(); // initialize an array named `pupilarray`
    while($row = mysqli_fetch_assoc($pupilquery)){
        $pupilarray[] = $row['Pupil_Name'];
               //  ^ push the value inside
    }
    

    Sidenote: And if your thinking you could just straight up echo the array (echo $pupilarray). No you cannot do that. Either use print_r() or var_dump() to see its contents.

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

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案