PHP - refreshing page and showing different rows in a table - php

<?php
//if pageNum isset figure out where to start(7 rows per page * page num +1
$pageNum = isset($_GET['pageNum']) ? (int)$_GET['pageNum'] : 0;
$startRow = $pageNum == 0 ? 0 : ($pageNum * 7 + 1);
$endRow = $startRow + 7;
$count = 0;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
if($count >= $startRow)
echo ' aantal vervangingen: 30';
$row = 1;
if (($handle = fopen("vervangingen.csv", "r")) !== FALSE) {
echo '<table border="1">';
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
if($count == $endRow)
{
//wait 3 seconds then use javascript to redirect.
sleep(3);
echo '<script>window.loaction.href="theurl?pageNum='.($pageNum +1).'"</script>';
}
}
?>
I made a table in php which gets the data from a .csv file. My question is, how do i let php show the first 7 rows, then it should refresh the page and show the following 7 rows, there are 30 in total. Once it has shown all the rows, it should still refresh the page and start all over again.
How do I do this? I know how to refresh a php page, but showing 7 rows per refresh is quite hard. Any help?
Greetings

The following (tested) uses PHP sessions and JS setTimeout.
Interesting, but I wonder if I will ever use this effect.
(I was unable to save the $handle as a session variable.)
<?php // z1.php is this file, z1.csv is the data file
session_start();
echo <<<EOD
<body onload="setTimeout('f1();',3000);">
<script type="text/javascript">
function f1() { window.location.replace("z1.php"); }
</script>
EOD;
if (isset($_SESSION['sessrow1st'])) { $row1st = $_SESSION['sessrow1st']; }
else { $row1st = 1; }
$handle = fopen("z1.csv", "r");
if ($handle === false) { exit("open error"); };
echo "<table border='1'>\n";
$rownum = 0;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$rownum += 1;
if ($rownum < $row1st) continue;
if ($rownum > $row1st+6) break;
$numcols = count($data);
echo '<tr>';
for ($c=0; $c < $numcols; $c++) {
if(empty($data[$c])) { $value = " "; }
else { $value = $data[$c]; }
echo '<td>'.$value.'</td>'; }
echo "</tr>\n"; }
echo '</table></body>';
if (feof($handle)) { $rownum = 1; }
fclose($handle);
$_SESSION['sessrow1st'] = $rownum;
?>

You can use Javascript's setTimeout and a get variable to accomplish this.
//if pageNum isset figure out where to start(7 rows per page * page num +1
$pageNum = isset($_GET['pageNum']) ? (int)$_GET['pageNum'] : 0;
$startRow = $pageNum == 0 ? 0 : ($pageNum * 7 + 1);
$endRow = $startRow + 7;
$count = 0;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
if($count >= $startRow)
{
$num = count($data);
if ($row == 1) {
echo '<tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
if($count == $endRow)
{
//make it dynamic...
$theUrl = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."?pageNum=".($pageNum+1);
//wait 3 seconds then use javascript to redirect.
echo '<script>setTimeout(function(){
window.location.href="'.$theUrl.'"}, 3000)
</script>';
}
++$count;
}
First step is figure out which page you're on, then display what you want, then use javascript redirect, as php redirect will fail after headers are sent. Also the setTimeout function is what controls the wait

Related

how to query a csv value in php?

I'm currently using this script:
<?php function jj_readcsv($filename, $header=false) { $handle = fopen($filename, "r"); echo '<table>'; //display header row if true if ($header) {
$csvcontents = fgetcsv($handle);
echo '<tr>';
foreach ($csvcontents as $headercolumn) {
echo "<th>$headercolumn</th>";
}
echo '</tr>'; } // displaying contents while ($csvcontents = fgetcsv($handle)) {
echo '<tr>';
foreach ($csvcontents as $column) {
echo "<td>$column</td>";
}
echo '</tr>'; } echo '</table>'; fclose($handle); } jj_readcsv('partitiontable.csv',true);
?>
I have a CSV table with 8 columns.
I would like to know if it possible to get only on element of the column when making a query. Here is what look like my CSV :
"HEMSI, Alberto",P_000001,P_1,Partition,169864,"Hemsi, Myriam","HEMSI, Alberto","Una matica de ruda",
"HEMSI, Alberto",P_000002,P_2,Partition,169865,"Hemsi, Myriam","HEMSI, Alberto","Ya salio de la mar",
the idea is :
query a value for example: P_1
and get in result: Una matica de ruda
For each line, when asking P_1 getting the value which is in the 8 column.
And the same for P_2
Yes, this is possible using two methods:
At the beginning create an associative array and insert as key the 4th column, and as value with 8th column. Then use this as a lookup table in all further code.
If you don't do 1. , you can make a for loop that goes through the CSV data and looks with IF that the 4th row value is the one you are looking for. When found, return the 8th column value.
Example of first approach with associative array
<?php
$array = array();
jj_readcsv("csv.txt");
echo $array["P_1"]."<br/>";
echo $array["P_2"]."<br/>";
function jj_readcsv($filename, $header = false)
{
global $array;
$row = 1;
if (($handle = fopen($filename, "r")) !== FALSE) {
echo '<table>'; //display header row if true if ($header) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//print_r($data);
$num = count($data);
echo '<tr>';
for ($c=0; $c < $num; $c++) {
if($row > 1)
echo "<td>$data[$c]</td>";
else
echo "<th>$data[$c]</th>";
if($c==2)
$array[$data[$c]]= $data[7];
}
echo '</tr>';
$row++;
}
fclose($handle);
}
}
?>
Try this:
$row = 1;
$handle = fopen ("teste.csv","r");
$head = Array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//register head rows with names
if($row == 1){
$num = count ($data);
for ($c=0; $c < $num; $c++) {
$colName = trim($data[$c]);
$head[$colName] = $c;
}
}else{
echo $data[$head['COL_NAME']];
}
$row++;
}
fclose ($handle);
This will make var $head an associative array where the key is the col name and value his position in csv, after that you can easy identify what col you want.
Even if you named your function jj_readcsv(), if you look more closely, this name is a liar, the function does much more: opening a file, reading the lines.
If you don't want to separate the concerns but also easily modify it, just make the actual reading method optional:
function jj_readcsv($filename, $header = FALSE, callable $fgetcsv = NULL)
########################
{
$fgetcsv || $fgetcsv = 'fgetcsv';
#################################
$fileHandle = fopen($filename, "r");
if (!$fileHandle) {
return;
}
$csvLine = $fgetcsv($fileHandle);
#####################
echo '<table>';
echo '<tr>';
foreach ($csvLine as $headercolumn) {
echo "<th>$headercolumn</th>";
}
echo '</tr>';
while ($csvLine = $fgetcsv($fileHandle)) {
#####################
echo '<tr>';
foreach ($csvLine as $column) {
echo "<td>$column</td>";
}
echo '</tr>';
}
echo '</table>';
fclose($fileHandle);
}
This little modification allows you to specify the reading function, therefore you can control what is read. So you can inject it as third parameter, for example to only return the eighth column:
jj_readcsv('test.csv', FALSE, function($fileHandle) {
if ($csvLine = fgetcsv($fileHandle))
{
$csvLine = [$csvLine[7]];
}
return $csvLine;
});
Output:
<table><tr><th>Una matica de ruda</th></tr><tr><td>Ya salio de la mar</td></tr></table>

CSV line stops after 22,000 when displaying file content using php fgetcvs

The csv file contains 37,000 lines but it only displays up to 22,000 lines
$csv = fopen('1'.'.csv','r') or die("can't find file");
echo "<table border=1 >";
echo "<tr><th>ID</th><th>Title</th><th>Gender</th><th>First</th><th>Middle</th><th>Last</th><th>Country Code</th><th>Primary Number</th><th>Secondary Number</th><th>Primary Address</th><th>Address 2</th><th>Address 3</th><th>City</th><th>State</th><th>Country</th><th>Zip</th><th>Email</th><th>Date of Birth</th><th></th><th>Bussiness Name</th><th>Business Number</th><th>Business Fax</th><th>Business Address</th><th>Business City</th><th>Business State</th><th>Businsess State</th><th>Notes</th></tr>";
while($csv_line = fgetcsv($csv,0)) {
if($id == 0){
list($column[0], $column[1], $column[2], $column[3], $column[4], $column[5], $column[6], $column[7],$column[8], $column[9], $column[10], $column[11], $column[12], $column[13], $column[14], $column[15],$column[16], $column[17], $column[18], $column[19], $column[20], $column[21], $column[22], $column[23], $column[24]) = $csv_line;
//===TO LOWER=====
for($col_n = 0;$col_n <= $arr_count; $col_n++) {
$col_lower[$col_n] = strtolower($column[$col_n]);
}
//===SORT VALUE=====
echo
'<tr><td>CODE:</td><td>';
for($col_n = 0;$col_n <= 16; $col_n++) {
echo $sort[$col_n].'</td><td>';
}
echo'</td><td>';
for($col_n = 17;$col_n <= $arr_count; $col_n++) {
echo $sort[$col_n].'</td><td>';
}
echo '</td></tr>';
for($col_n = 0;$col_n <= $arr_count; $col_n++) {
for($sort_n = 0;$sort_n <= $arr_count; $sort_n++) {
if($sort[$col_n] == $col_lower[$sort_n]){
$col[$col_n] = $sort_n;
}
}
}
}
if($id > 0){
list($column[0], $column[1], $column[2], $column[3], $column[4], $column[5], $column[6], $column[7],$column[8], $column[9], $column[10], $column[11], $column[12], $column[13], $column[14], $column[15],$column[16], $column[17], $column[18], $column[19], $column[20], $column[21], $column[22], $column[23], $column[24]) = $csv_line;
//===ECHO=====
echo
'<tr><td>'.
$id.'</td><td>';
for($col_n = 0;$col_n <= 16; $col_n++) {
$data = ucwords(strtolower($column[$col[$col_n]]));
echo $data.'</td><td>';
}
echo '</td><td>';
for($col_n = 17;$col_n <= $arr_count; $col_n++) {
$data = ucwords(strtolower($column[$col[$col_n]]));
echo $data.'</td><td>';
}
echo '</td></tr>';
}
$id++;
}
echo "</table>";
}
found the answer:
ini_set('memory_limit', '512M');
ini_set('max_execution_time', '180');
add this line on the top of your php file to adjust execution time and memory limit.

SQL being executed twice in FOR loop

I think I need a second pair of eyes on this one. For the life of me I can't figure out why my SQL INSERT query is running twice every iteration:
if (($handle = fopen($spreadsheet_url, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($current_row == 1 || $current_row == 2) {
$num = count($data);
//echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
try {
set_time_limit(0);
$stmt = $db_temp_kalio->prepare('INSERT INTO invupdate (sku,prod) VALUES(:sku, :prod)');
$stmt->execute(array(':sku'=> $data[0], ':prod'=> $data[1])); }
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
exit; }
}
}
$current_row++;
}
fclose($handle);
}
Well, I probably should have put forth a little more effort before asking for assistance. I was able to fix this by adding a row reset counter in the loop:
if (($handle = fopen($spreadsheet_url, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($current_row == 1 || $current_row == 2) {
$row_reset = 0;
$num = count($data);
//echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if ($row_reset == 0) {
try {
set_time_limit(0);
$stmt = $db_temp_kalio->prepare('INSERT INTO invupdate (sku,prod) VALUES(:sku, :prod)');
$stmt->execute(array(':sku'=> $data[0], ':prod'=> $data[1])); }
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
exit; }
}
$row_reset++;
}
}
$current_row++;
}
fclose($handle);
}
I'm still curious if there is a better way.
I looks like you were using some code to iterate through your columns, but actually only have two, containing the sku and prod ($data[0] and $data[1].) If that is the case, then you don't need the for loop inside. (BTW, it was that loop that was causing the query to be executed twice, as the query was inside it.) It also looks like you have two counters going for the row (current_row and row) so those can be combined. If you are using the if ($currentRow == 1... statement to ignore the header on row 0 and then only process 2 rows, you will want to switch it to if ($currentRow > 0) when you are ready to run the whole spreadsheet. Using break in the catch clause instead of exit will cause the code to drop out of the while loop and hit the fclose statement:
if (($handle = fopen($spreadsheet_url, "r")) !== FALSE) {
$currentRow = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($currentRow == 1 || $currentRow == 2) {
$num = count($data);
//echo "<p> $num fields in line $currentRow: <br /></p>\n";
//echo "<p> The data for this row is: " . $data[0] . " " . $data[1] . "\n";
try {
set_time_limit(0);
$stmt = $db_temp_kalio->prepare('INSERT INTO invupdate (sku,prod) VALUES(:sku, :prod)');
$stmt->execute(array(':sku'=> $data[0], ':prod'=> $data[1]));
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
break;
}
}
$currentRow++;
}
fclose($handle);
}

Create HTML table from multiple lines of strings

I want to take a text file formatted like so:
*note I can change the format of the stored messages, basically there are delimiters and different lines
;68.229.164.10:4/5/2013:Hello
;71.73.174.13:4/6/2013:Oh Hey
(;IPADDRESS:TIMESTAMP:MESSAGE)
and put it in a table that looks like so:
IP Time Message
68.229.164.10 4/6/2013 Hello
71.73.174.13 4/6/2013 Oh Hey
I prefer to use something like the following:
http://php.net/manual/en/function.fgetcsv.php
And then format the output accordingly.
From Example 1 on the above referenced page:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
so, you could do something like this...
<?php
$row = 1;
if (($handle = fopen("path_to_your_data_file", "r")) !== FALSE) {
echo '<table>';
echo '<tr><td></td>IP<td>Time</td><td>Message</td></tr>';
while (($data = fgetcsv($handle, 1000, ":")) !== FALSE) {
$num = count($data);
$row++;
if ($num > 2) {
echo '<tr>';
for ($c=0; $c < $num; $c++) {
echo '<td>'.$data[$c].'</td>';
}
echo '</tr>';
}
}
echo '</table>';
fclose($handle);
}
?>
$a=";68.229.164.10:4/5/2013:Hello
;71.73.174.13:4/6/2013:Oh Hey";
preg_match_all('{;(.*?):(.*?):(.*)}',$a,$d);
//set th
$d[0][0]='IP';
$d[0][1]='TIME';
$d[0][2]='Message';
$table = '<table>'.PHP_EOL;
foreach($d AS $tr){
$row = PHP_EOL;
foreach($tr AS $td){
$row .= "<td>{$td}</td>".PHP_EOL;
}
$table .= "<tr>{$row}</tr>".PHP_EOL;
}
$table .= "</table>".PHP_EOL;
echo $table;

simple for loop help needed in php

I have 568 rows in my csv file and my for loop looks like this
$csv = array();
$file = fopen('names.csv', 'r');
while (($result = fgetcsv($file)) !== false)
{
$csv[] = $result;
}
fclose($file);
for ($row = 0; $row < 568; $row++)
{
echo "Serial no:<br/>";
echo "Name:".$csv[$row][1]."";
}
I want the output like this...
Serial no: 1
Name: Blah blah 1
Serial no: 2
Name: Blah blah 2
............
............
Serial no: 10
Name: Blah blah 10
For each 10 rows i want serial 1 to 10.. Once it finished 10 rows i want a horizontal line..
I mean i want to print
echo "<hr>";
For every 10 rows..
Can anyone help me?
Thanks
This should work :
for ($row = 0; $row < 568; $row++) {
echo "Serial no:<br/>";
echo "Name:".$csv[$row][1];
echo (($row+1)%10 == 0) ? '<hr>' : '<br />';
}
Explanation :
You don't need that ."" at the end of your "Name" line.
$row + 1 : instead of $row to avoid printing an <hr> after the first element (pos 0)
echo (condition) ? res1 : res 2; is like if (condition) echo res1; else echo res2;
But the real good way to do this would be :
$file = fopen('names.csv', 'r');
$i = 1;
while (($result = fgetcsv($file)) !== false) {
echo "Serial no:" .$i. "<br/>";
echo "Name:".$result[1];
echo ($i == 1) ? '<hr>' : '<br />';
$i = ($i%10)+1;
}
fclose($file);
$csv = array();
$file = fopen('names.csv', 'r');
while (($result = fgetcsv($file)) !== false)
{
$csv[] = $result;
}
fclose($file);
for ($row = 0; $row < 568; $row++)
{
echo "Serial no:<br/>";
echo "Name:".$csv[$row][1]."";
if ((int) $row % 10 === 0)
{
echo '<hr>';
}
}
Should do the trick :)

Categories