dongping4901 2012-08-26 05:05
浏览 21
已采纳

在HTML表中显示mySQL行,而无需单独指定每个列

I'm creating a form where users can view and edit their account information and I'd like to streamline this as much as possible since there are a lot of form fields. I've selected all the customer's data without specifying the column names, but I'm having trouble displaying in the correct place in an HTML table without having to call each one individually.

I've used mysql_fetch_array in the code below, but it would be quite cumbersome to do for 300+ fields. I know that mysql_fetch_assoc can be used, but I haven't figured out how to then print in the correct place.

mysql_fetch_assoc (Pardon my ignorance, but I couldn't get this to work without using WHILE and FOREACH)

while ($row = mysql_fetch_assoc($result)) {
foreach($row as $key=>$value){    
echo "$key: $value<br />
 ";            
}}

This works but requires specifying each field individually

<?php  
//Database connection and Open database
require_once('config.php');   
$result = mysql_query("SELECT customer_info.*, style.* FROM customer_info, style WHERE customer_info.user_id = style.user_id AND customer_info.user_id=$user_id ") or die(mysql_error());
$row = mysql_fetch_array($result );
?>

<table border="0" cellspacing="2" cellpadding="2">
<tr><td name="fname">First Name: <?php echo $row['fname']; ?></td>
<td name="lname">Last Name: <?php echo $row['lname']; ?></td>
<td name="email">Email: <?php echo $row['email']; ?></td>
<td name="colors_love">Colors Love: <?php echo $row['colors_love']; ?></td>
</tr></table>

Is there a way to essentially reverse the way I achieve this with my INSERT INTO code? if so, I'm assuming that will simplify my next task (allowing users to edit their information)

$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.($value).'\',';
}
$result = mysql_query('INSERT INTO taste ('.$fieldlist.') VALUES ('.$vallist.')');
  • 写回答

2条回答 默认 最新

  • douyu53265 2012-08-26 05:16
    关注

    Leaving out the fact that using the mysql library is a terrible idea, you're actually most of the way there:

    <table>
        <?php while ($row = mysql_fetch_assoc($result)): ?>
        <tr>
            <?php foreach($row as $key=>$value) {   
                echo "<td>$key: $value</td>
     "; 
            } ?> 
        </tr>          
        <?php endwhile; ?>
    </table>
    

    You obviously would want to clean this up for a real form, since echoing db field names isn't exactly user-friendly.

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

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?