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.')');
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.
kind of this?
<?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_assoc($result );
?>
<table border="0" cellspacing="2" cellpadding="2">
<tr><?php foreach($row as $field => $content): ?>
<td><?php echo $field; ?>: <?php echo $content; ?></td>
<?php endforeach; ?></tr>
</table>