Create/fill form with values from uploaded CSV - php

I've decided that to accomplish my task, I need to take the CSV file that is uploaded on my first page, and build a form from it filling the inputs with the CSV values.
I have a functioning CSV upload, but this is to view the CSV and make edits to the fields before saving. I have a while loop that I think I should build the form inside. The only trick is that I've built a CSV data array that handles it upon upload and it's 229 elements long. I need to build the form names to mirror it, so I"ll essentilally be naming 229 form fields, which is fine. Here is the current code that successfully loads the CSV into a table when the button is clicked:
$file = $_FILES["file"]["tmp_name"];
$handle = fopen($file, "r");
$maxPreviewRows = PHP_INT_MAX; // this will be ~2 billion on 32-bit system, or ~9 quintillion on 64-bit system
$hasHeaderRow = true;
echo '<table>';
/*WE WILL NEED TO QA CONDITIONS AND HIGHLIGHT IN RED HERE. ALSO NEED BORDER STYLINGS*/
if ($hasHeaderRow) {
$headerRow = fgetcsv($handle);
echo '<thead><tr>';
foreach($headerRow as $value) {
echo "<th>$value</th>";
}
echo '</tr></thead>';
}
echo '<tbody>';
$rowCount = 0;
while ($row = fgetcsv($handle)) {
echo '<tr>';
foreach($row as $value) {
echo "<td>$value</td>";
}
echo '</tr>';
if (++$rowCount > $maxPreviewRows) {
break;
}
}
echo '</tbody></table>';
}
So, that successfully shows the entire CSV (6 rows, 229 columns per row) for a preview. Now I just need to make each field editable and then insert the entire form upon submit. I know how to insert a form to a database, so now I just need an idea of how to build the form within the while loop and create the names for each input, as well as how to fill the inputs with the actual CSV data.

This is how you can create a form. Each form element is named like row1col1, row1col2, ro1col3 etc...
$file = $_FILES["file"]["tmp_name"];
$handle = fopen($file, "r");
$maxPreviewRows = PHP_INT_MAX; // this will be ~2 billion on 32-bit system, or ~9 quintillion on 64-bit system
$hasHeaderRow = true;
echo '<form>\n';
echo '<table>';
/*WE WILL NEED TO QA CONDITIONS AND HIGHLIGHT IN RED HERE. ALSO NEED BORDER STYLINGS*/
if ($hasHeaderRow) {
$headerRow = fgetcsv($handle);
echo '<thead><tr>';
foreach($headerRow as $value) {
echo "<th>$value</th>";
}
echo '</tr></thead>';
}
echo '<tbody>';
$rowCount = 0;
while ($row = fgetcsv($handle)) {
$colCount = 0;
echo '<tr>';
foreach($row as $value) {
echo "<td><input name='row".$rowCount."col".$colCount."' type='text' value='$value' /></td>";
$colCount++;
}
echo '</tr>';
if (++$rowCount > $maxPreviewRows) {
break;
}
}
echo '</tbody></table>';
echo '<input type=\'submit\' value=\'Submit\' >';
echo '</form>';

Related

Displaying data from arrays in a dynamic table PHP

I have a file with 20 pictures of country artists, and a text file with their websites. I'm trying to display this data in a 4 row 5 column table using PHP.
I try to use a foreach loop that iterates for every 5 elements in the array
(to load each row one by one)
foreach(array_chunk($CountryArtists, 5, true) as $Value) {
<table>
<tr><td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td></tr>
</table>
Ive been trying to figure out how to load the images into the array, but having no luck. Im starting to think i must put the reference to the file location in the array,but i am not sure.
$colsToDisplay = 5;
$CountryArtists = array("C:\Users\THEFOLDER\images");
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", RTravis", "STwain", TKeith", TMcgraw");
$filename = "C:\Users\THEFOLDER\images";
I'm relatively new to PHP and really just need to know how to load my images and how to make this table show up correctly.
EDIT:
I added echo to the table lines but it just shows echo in the browser output:
" echo " $CountryArtists[$Value] $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo "" } ?>
My code now looks like this:
foreach(array_chunk($CountryArtists, 5, true) as $Value) {
echo "<table>"
echo "<tr><td> $CountryArtists[$Value] $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td></tr>"
echo "</table>"
}
I feel like I'm doing strong wrong, would be so grateful to have it pointed out to me.
FULL FILE
<!DOCTYPE HTML>
<html>
<body>
<?php
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", "RTravis", "STwain", "TKeith", "TMcgraw");
$count = count($ArtistImages);
$cols = 6;
$div = (int) $count / (int)$cols;
$diff = ceil($div);
echo
$fin = $cols * $diff;
$a = 1;
echo '<table>';
for($i = 0; $i < $fin; $i++) {
if($a == 1)
echo "\t<tr>".PHP_EOL;
$artist = (!empty($ArtistImages[$i]))? $ArtistImages[$i]: "";
echo "\t\t".'<td>'.$artist.'</td>'.PHP_EOL;
if($a == $cols) {
echo "\t</tr>".PHP_EOL;
$a=0;
}
$a++;
}
echo '</table>';
?>
</body>
</html>
I think you may be looking for something similar to this algorithm. It adds a row every 5 values. You will want to do a divisor make it ceil() to make it add any required empty cells. You can do this foreach if you do <ul> and <li> and use CSS to make them display like a table. Then you don't need to calculate extra cells.
$i = 1;
echo '<table>';
foreach($array as $value) {
if($i == 1)
echo "<tr>";
echo '<td>'.$value.'</td>';
if($i == 5) {
echo "</tr>";
$i=0;
}
$i++;
}
echo '</table>';
EDIT:
Here is a more practical version based on yours:
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", "RTravis", "STwain", "TKeith", "TMcgraw");
// Count total artists in array
$count = count($ArtistImages);
// Choose how many to display per row
$cols = 6;
// Divide the total by the columns
$div = (int) $count / (int)$cols;
// Round up (incase the number will produce empty cells
$diff = ceil($div);
// Mulitply the final numbers
$fin = $cols * $diff;
// Create an autoincrementer to keep track of next rows
$a = 1;
echo '<table>'.PHP_EOL;
for($i = 0; $i < $fin; $i++) {
if($a == 1)
echo "\t<tr>".PHP_EOL;
// You need to see if this artist is populated. If not, make empty
// If left without this it will have a warning saying not exists
$artist = (!empty($ArtistImages[$i]))? $ArtistImages[$i]: "";
echo "\t\t".'<td>'.$artist.'</td>'.PHP_EOL;
if($a == $cols) {
echo "\t</tr>".PHP_EOL;
$a=0;
}
$a++;
}
echo '</table>';
In the php file you need to echo the data you want.
However if you in the php file you can close php like this.
? >
And write html code.
When you want to display php attributes you again need to open a php like this:
and continue like this...
Php fcan only return string or json data
Let me know if it work for you....

Reading text file and checkboxes - PHP

Basically the code below reads in a text file and diplays it on the screen with checkboxes near each line. But now I want the user to be able to check any box and then display the selected results in a new PHP file - I thought I would have to read in the text file again and somehow refer it to the array, but I'm still stuck, so any help would be appreciated.
Thank you.
First php file
<?php
$filename = "file.txt";
$myarray = file($filename);
print "<form action='file2.php' method='post'>\n";
// get number of elements in array with count
$count = 0; // Foreach with counter is probably best here
foreach ($myarray as $line) {
$count++; // increment the counter
$par = getvalue($line);
if ($par[1] <= 200) {
// Note the [] after the input name
print "<input type='checkbox' name='test[$count]' /> ";
print $par[0]." ";
print $par[1]." ";
print $par[2]." ";
print $par[3]."<br />\n";
}
}
print "</form>";
Second php file which should display the selected results
<?php
$filename = "file.txt";
$myarray = file($filename);
?>
I think you're over complicating the problem. You can just give the checkboxes a value atribute and read the array from the second page. Start with kus print_r ($_POST) on the second page to help you see what you have to work with.
1) Think of format of your text file (could be something like "Name1-Value 1-true\nName1-Value2-false")
2) Learn this function
3) Create a file with the default options
4) Make a PHP script that opens the file, makes an array and prints the resoult - for example:
$handle = fopen('./file.txt','r');
$fileString = fread($handle,filesize('./file.txt'));
$handle = null; //Similar to unset($handle);
$array = explode($fileString, "\n");
echo '<form action="./script2.php">';
foreach ($array as $value) {
$value = explode($value, "-");
echo '<input type="checkbox" name="'.$value[1].'" value="'.$value[2].'" checked="';
if ($value[3]==true) {
echo 'checked" /><br />';
} else {
echo '" /><br />';
}
}
5) Make the second script that edits the file - for example:
if ($_GET == null;) {exit("He's dead, Jim!");}
$handle = fopen('./file.txt','r');
$fileString = fread($handle,filesize('./file.txt'));
//Do something with the string :D
$handle = fopen('./file.txt','w');
fwrite($handle,$fileString);

Populate table from excel file using php

I am trying to use data from an excel spreasheet to populate an html table using php. I am a beginner at PHP. I have tried to use code from other questions, and they were close but not quite what I needed. The excel document will be periodically updated by another person.
Here's an example of code I've used:
$file = file("/calendar.txt");
print "<table>
<tr><td>Date</td><td>Start Time</td><td>Venue</td><td>Description</td></tr>";
foreach($file as $line){
$line = trim($line);
$split = mb_split("\t",$line);
print "<tr><td>$split[3]</td><td>$split[4]</td><td>$split[5]</td><td>$split[6]</td></tr>";
}
print "</table>";
?>
But the above example does not allow for auto-population. So I tried this:
<table>
<?php
if (($handle = fopen("/calendar.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
print "<tr><td> $data[$c] </td></tr>";
}
}
fclose($handle);
}
?>
</table>
But I couldn't get the columns I wanted. Plus both examples did not allow for a new row/column created at the end of the last column from the source file (i.e. the data from the last column in the first row is combined with the first column of the second row).
I would also like to echo the line, "There are no upcoming dates currently. Please check back soon!" if there is no information to display. And is there a way to do a colspan in php? Here are my failed attempts: http://www.tonejones.com/calendar3.php
I want the table to look like this: http://www.tonejones.com/calendar.php
To populate Data from Excel to Table. First We need to retrieve all data into Array then we will render all Array values into table.Get reference to retrieve data into array. https://www.studytutorial.in/how-to-upload-or-import-an-excel-file-into-mysql-database-using-spout-library-using-php. IF you get array then use below code
<table>
<?php foreach($rows as $value){ ?>
<tr>
<td><?php echo $value; ?></td>
</tr>
<?php } ?>
</table>
Your block should go around the collection of cells, not each individual cell:
print "<table>
<tr><td>Date</td><td>Start Time</td><td>Venue</td><td>Description</td></tr>";
<?php
if (($handle = fopen("/calendar.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
$num = count($data);
print "<tr>";
for ($c=3; $c < $num; $c++) {
print "<td> $data[$c] </td>";
}
print "<tr>";
}
fclose($handle);
} else {
print "<tr><tdcolspan="4">
There are no upcoming dates currently. Please check back soon!
</td></tr>";
}
?>
</table>

Check if variable contents exist in array displayed in table?

I am creating an in-house order pulling application. I'm pulling form an ODBC source and placing items in an array. I'm then creating a new flat file for each order being physically worked on. When the user scans/enters an item from that order number it places that item on a new line in the order file that was created.
I'm then reading that order file back to get the items that have been scanned thus far. Where I'm stuck is how to mark that line item that exist in the order file as being completed in the HTML table.
Here is the pertinent code as it relates to my question:
$file_array = file_get_contents($file_ordnumber, "rb");
$items_array = explode("\n",$file_array);
echo "<table>";
for ($i = 0; $i < count($location_array); $i++)
{
echo "<tr>";
if (in_array("$itemno_array[$i]", $items_array)) {
echo "<td>$itemno_array[$i] EXISTS</td>";
}
else {
echo "<td>$itemno_array[$i] NO EXIST</td>";
}
// echo "<td>$location_array[$i]</td>";
echo "<td>$qty_array[$i]";
echo "<td>$pickingseq_array[$i]</td>";
echo "</tr>";
}
echo "</table>";
As you can see I'm iterating through the array and displaying it in a HTML table. I'm curious why my above code isn't working. My result ends up being from the 'else' statement thus ALL lines, even if they exist in the file is showing as "NO EXIST" which is obviously incorrect.
Can you post your Print_r($items_arr);
also try using isset($arrayVar[$key]
and try removing double quotes and see if it works.. like ...
$file_array = file_get_contents($file_ordnumber, "rb");
$items_array = explode("\n",$file_array);
echo "<table>";
for ($i = 0; $i < count($location_array); $i++)
{
echo "<tr>";
if (in_array($itemno_array[$i], $items_array)) {
echo "<td>".$itemno_array[$i]." EXISTS</td>";
}
else {
echo "<td>".$itemno_array[$i]." NO EXIST</td>";
}
// echo "<td>".$location_array[$i]."</td>";
echo "<td>".$qty_array[$i]."";
echo "<td>".$pickingseq_array[$i]."</td>";
echo "</tr>";
}
echo "</table>";
I got this resolved by going about it a different way. I use strpos() to search the flat file itself rather than the array that I exploded from it:
echo "<table>";
//for ($i = 0; $i < count($itemno_array); $i++)
for($i=0;$i<sizeof($itemno_array);$i++)
{
echo "<tr>";
// if (in_array($itemno_array[$i], $items_array)) {
echo "<td>";
$var = $itemno_array[$i];
$newvar = trim($var);
if(strpos($file_array, $newvar ) !==FALSE) {
echo "$var ** EXISTS</td>";
}
else {
echo "$var DOES NOT EXIST **</td>";
}
// echo "<td>$location_array[$i]</td>";
echo "<td>$qty_array[$i]";
echo "<td>$pickingseq_array[$i]</td>";
echo "</tr>";
}
echo "</table>";

Library to print tabular data on a web page

Are there any libraries I can use to pretty print tabular data(from php code)?
What I mean is, if I have:
$headers = array("name", "surname", "email");
$data[0] = array("bill", "gates", "bill#microsoft.com");
$data[1] = array("steve", "jobs", "steve#apple.com");
/*...*/
pretty_print($headers, $data);
It will print my data neatly(preferably using tableless html code & css)?
Why not just write your own?
I wrote an example below. Note that I haven't tested this - it's the definition of "air code" so beware. Also, you could add checks to make sure count($rows) > 0 or to make sure count($rows) == count($headers) or whatever..
The point is just that it isn't that hard to throw something together:
function displayTable($headings, $rows) {
if !(is_array($headings) && is_array($data)) {
return false; //or throw new exception.. whatever
}
echo "<table>\n";
echo "<thead>\n";
echo "<tr>\n";
foreach($headings as $heading) {
echo "<th>" . $heading . "</th>\n";
}
echo "</tr>\n";
echo "</thead>\n";
echo "<tbody>"
foreach($data as $row) {
echo "<tr>\n";
foreach($row as $data) {
echo "<td>" . $data . "<td>";
}
echo "</tr>\n";
}
echo "</tbody>\n";
echo "</table>\n";
}
As a final note, why would you want to use HTML/CSS layouts rather than tables for this? Tables are for tabular data which this obviously is. This is their purpose!
The trend against using tables is for using them to layout pages. They're still quite valid for tabular data, and will be for the foreseeable future.

Categories