Reputation: 147
I have a simple form that the contents are populated by pulling data from the database. I use a multi name[] option so I can loop through the data in PHP easily. The form may expand in future so I do not want to reuse code in the PHP end. I am making a csv from the outputted data and want to create header names on the csv file from the $_POST array() I can access the data but it populates a new row in the csv file instead of a new column.I would also like to output the data from the posted data to new rows. I have tried a few things which I have commented in the code of the result I got when I tried them.
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
foreach ($_POST as $key => $value)
{
//This is where I want to add the $_POST values as headers
fputcsv($output, array($Key));//This is what I have tried but it just adds in a new line not column
}
//I have also tried the following for the rows to add the data into the csv file
for ( $i = 0; $i < count($_POST) - 0; ++$i)
{
foreach ($_POST as $key => $value)
{
fputcsv($output, array($Key[$i])); //This seems to only return the first character
}
}//End of for loop
?>
<!-- form is to be populated from a mysql data base in a table -->
<!-- This pulls the data from the database and loops throgh and displays the data. -->
<form action = "" method = "Post">
<?php while ($row = $prepped->fetch(PDO::FETCH_OBJ)) :?>
<input type="text" name="Firstname[]" value="<?php echo $row->Firstname ; ?>">
<input type="text" name="Email[]" value="<?php echo $row->Email ; ?>">
<input type="text" name="LastName[]" value="<?php echo $row->Lastname ; ?>">
<input type="text" name="Phone[]" value="<?php echo $row->Phone ; ?>">
<?php endwhile;?>
</form>
Upvotes: 3
Views: 247
Reputation: 1
$keys=array_keys($_POST);
fputcsv($output, array_keys($_POST));
do {
$result=array();
$i++;
foreach($keys as $key => $value){
$result[]=$_POST[$value][$i];
}
fputcsv($output, $result);
}
while ($i = 0; $i < count($_POST));
exit();
Upvotes: -1
Reputation: 216
$keys=array_keys($_POST);
fputcsv($output, array_keys($_POST));
for ($i = 0; $i < count($_POST); $i++)
{
$result=array();
foreach($keys as $key => $value)
{
$result[]=$_POST[$value][$i];
}
fputcsv($output, $result);
}
exit();
You will get key as column name and value as row
Upvotes: 2