douzhou7037 2015-11-16 21:32
浏览 32
已采纳

如何使用php迭代整个mysql表

I want to iterate through all the records of mysql table. Here's how my table looks like

enter image description here

So I want to print out the name of the user and the subject of the post they posted. I have another user table. Here's my php code.

require_once('config.php');
    // build SQL query
            $sql ="SELECT user_id, subject FROM post"; 
            $result = mysqli_query($conn, $sql);
            $row = mysqli_fetch_assoc($result);

            foreach ($row as $k => $v) {
                if($k == 'user_id'){

                    $uid = $v;
                    $sql2 ="SELECT '$db', username FROM users WHERE user_id='$uid'"; 
                    $result2 = mysqli_query($conn, $sql2);
                    $row2 = mysqli_fetch_row($result2);
                    echo $row2[1]. " posted ";

                }
                if ($k == 'subject') {

                    echo "<a href='#'> $v </a>";
                }
            }

I am using the user_id to find the user in my other table. Pretty much a noob here. However I only get one output. enter image description here

However there should have been 2 outputs. because my post table contains 2 posts made by 2 different users. I only get the first post as an output. can someone please point me to right direction. Also how do I iterate a SQL table for all the records.

  • 写回答

2条回答 默认 最新

  • dongyejun1983 2015-11-16 21:53
    关注

    If you expect your query to return more than 1 result, you should call mysqli_fetch_assoc in a while loop.

    Also, you can use a JOIN query to return all the data in a single query:

    $sql = "SELECT post.subject, users.username 
            FROM post JOIN users 
            ON post.user_id = users.user_id"; 
    $result = mysqli_query($conn, $sql);
    while($row = mysqli_fetch_assoc($result)){
        echo sprintf("<p>%s posted <a href='#'>%s</a></p>", $row['username'], $row['subject']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵