Reputation: 14490
I am trying to parse all the column fields and data of a single row of any selected mysql table.
The reason behind this is to make a 'universal'-like Table parser of any given single row.
For example I have this table 'tbl1':
+----+---------------------+---------+---------+--+
| id | date | amounta | amountb | |
+----+---------------------+---------+---------+--+
| 1 | 2014-02-28 05:58:41 | 148 | 220 | |
+----+---------------------+---------+---------+--+
| 2 | 2014-01-20 05:58:41 | 50 | 285 | |
+----+---------------------+---------+---------+--+
| 3 | 2014-03-30 05:58:41 | 501 | 582 | |
+----+---------------------+---------+---------+--+
and I want to be able to select table tbl1 and id = 1 to export into:
<label>id <input type="text" value="1"/></label>
<label>date <input type="text" value="2014-02-28 05:58:41"/></label>
<label>amounta <input type="text" value="148"/></label>
<label>amountb <input type="text" value="220"/></label>
This is what I have thus far:
if ($_GET['p'] && $_GET['table']) {
include ("con.php");
$query = "SELECT * FROM `" . $_GET['table'] . "` WHERE id = '" . $_GET['p'] . "'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$fields[] = $row['0'];
$p = $row;
}
$fields = array();
$res = mysql_query("SHOW COLUMNS FROM `" . $_GET['table'] . "`");
while ($x = mysql_fetch_assoc($res)) {
$fields[] = $x['Field'];
}
foreach($fields as $f) {
foreach($p as $obj) {
echo '<label>' . $f . ' <input type="text" value="' . $p[$f] . '"></label>';
};
}
mysql_close();
}
The problem I'm sure is somewhere between the foreach looping. I know its totally wrong but im not quite sure how to solve this problem.
Basically the idea is to select all column names from $_GET['table'] and for each column name find its value where id = $_GET['p'];
Upvotes: 0
Views: 1772
Reputation: 2344
if $p
is a single-level array like
Array (
'field1' => 'value1',
'field2' => 'value2',
...
)
and $fields
is an array like this
Array (
0 => 'field1',
1 => 'field2',
...
)
Then this should work
foreach($fields as $f) {
echo '<label>' . $f . ' <input type="text" value="' . $p[$f] . '"></label>';
}
Upvotes: 0
Reputation: 324620
Use mysql_fetch_field
.
$fields = array();
while($f = mysql_fetch_field($query)) $fields[] = $f->name;
In this way you can get all field names, works for any kind of query rather than just SELECT *
Upvotes: 0