Adding/Incrementing data from a text file - php

I have a php file that contains some data when checked displays the checked data. How do I increment the variable "$visit" every time it is visited and save it to the text file?
new.php
<html>
<body bgcolor="#99FF00">
<table border="1">
<FORM ACTION="new.php" METHOD="POST">
Enter maximum price <input type="text" name="maximumprice"/>
<p><input type="submit" value="Go" name="Go"/>
</form>
<?
$mPrice = $_POST['maximumprice'];
$file1 = "properties.txt";
$filedata = fopen ($file1, "r");
$array1 = file ($file1);
print "<form action=\"visit.php\" method=\"POST\">";
for ($counter1 = 0; $counter1 < count($array1); $counter1++)
{
$arrLine = $array1[$counter1];
$pCode = getvalue ($arrLine, 0);
$price = getvalue ($arrLine, 1);
$picture = getvalue ($arrLine, 2);
$visit = getvalue ($arrLine, 3);
if ($price < $mPrice)
{
print "<tr>";
print "<td>";
print $pCode. "<br>";
print $price. "<br>";
//print $picture. "<br>";
print $visit. "<br>";
print "<input type=\"checkbox\" name=\"box[]\" value=\"$arrLine\" />";
print "</td>";
print "<td>";
printf("<img src='$picture' width='200' height='150'>");
print "</td>";
print "</tr>";
}
}
print '<input type="submit" name="Visit" value="Visit"/>';
// Move the form outside the for loop
print "</form>";
fclose ($filedata);
function getvalue ($text, $arrNo)
{
$intoarray = explode (",", $text);
return $intoarray[$arrNo];
}
?>
</table>
</body>
</html>
this is the second page, display.php
<html>
<body bgcolor="#99FF00">
<?
foreach ($_POST['box'] as $values)
{
echo "$values <hr/>";
}
?>
</body>
</html>

Step 1: Use a database :-)
No, but really, since you are storing the entire line as the value of the checkbox, you can compare that to the line in the file and update your visit field for matching lines ...
For example, in your processing file:
$filename = "properties.txt";
$data = file($filename, FILE_IGNORE_NEW_LINES);
$checked = $_POST['box'];
foreach($data as $id => $line){
if(in_array($line, $checked)){
//Explode the line into parts
$tmp = explode(',', $line);
//Increment the visit field
$tmp[3]++;
//Put the updated data back in the file data array
$data[$id] = implode(',', $tmp);
//Unset the tmp array
unset($tmp);
}
}
//implode the data back into a text block
$data = implode("\n",$data);
file_put_contents($filename, $data);
This is untested, but should yield what you are looking for ...
As a side note, you do not have to do the fopen call to use the file function. It will open and read the file.
EDIT: Since it appears that visit is the last column in each row and without any flags, the file function will keep the newlines at the end of each line, I added the appropriate flag to the file function.

Related

I am unsure what kind of loop to use in php

I am newer to PHP and I am able to get the desired output but I am doing it one index position at a time. I am returning data from a .txt file and I need to insert this data into an HTML table I am creating using PHP. BUT FIRST I need to be able to get the same output without typing out every index position. I tried to use a forloop but it kept outputting only one line.
I manually outputted the lines from the file and it works. What loop in PHP would be best to achieve the same results and output these elements? IMPORTANT, as is I am able to sort and rsort (I want to be able to do this so if it can be implemented in the loop that would be awesome) any help is more than I have right now.
PHP
$books = array();
if ($fp)
{
while(true)
{
$lines_in_file = count(file($filename));
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
list($title, $author, $pubdate, $isbn) = explode('*', $line);
$new_line = explode('*', $line);
for($ii= 1; $ii <= $lines_in_file; $ii++){
$lines = fgets($fp); //Read each line
$member = trim($lines);
array_push($books, $member);
}
//This foreach only brings back the first like in the txt file, why?
$cntr = 0;
foreach($books as $element){
$cntr++;
$table .= "<tr>";
$table .= "<td>".$title."</td>";
$table .= "<td>".$author."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$isbn."</td>";
$table .= "</tr>\n"; //added newline
echo $element;
}
//sort($books);
// rsort($books);
echo $books[0];
echo "<br>";
echo $books[1];
echo "<br>";
echo $books[2];
echo "<br>";
echo $books[3];
echo "<br>";
echo $books[4];
echo "<br>";
echo $books[5];
echo "<br>";
echo $books[6];
echo "<br>";
echo $books[7];
echo "<br>";
echo $books[8];
echo "<br>";
echo $books[9];
echo "<br>";
echo $books[10];
echo "<br>";
echo $books[11];
echo "<br>";
echo $books[12];
echo "<br>";
echo $books[13];
echo "<br>";
echo $books[14];
echo "<br>";
echo $books[15];
echo "<br>";
echo $books[16];
echo "<br>";
echo $books[17];
}//END WHILE LOOP
fclose($fp ); //Close file
}
Having to make a few guesses here but i believe the file is going to look like:
title*author*pubdate*isbn
title*author*pubdate*isbn
title*author*pubdate*isb
if this is wrong, let me know
as long as the fie is not to large read it in to an array:
$book_array=file('book_file.txt');
//print_r($book_array); //is it an array of the books, one book per array key
now to separate each line:
foreach($book_array as $line){
$line_sep=explode('*',$line);
// with no sorting option you could just echo inside the loop
//if you want to keep sorting options we have to keep the separated lines
$new_book_array[]=$line_sep;
}
unset($book_array);//free up memory if needed
//print_r($new_book_array);//is it a multi-d array, book then the 4 elements
to sort our new multidimensoanl array:
usort($new_book_array, function($a, $b) {
return strcmp($a['0'], $b['0']);;
}); //this sorts on key 0 in your case title:
//print_r($new_book_array); // has it sorted properly
for display:
loop again
echo '<table><tr><th>Title</th><th>Author</th><th>Pub Date</th><th>ISBN</th></tr>';
foreach($new_book_array as $book){
//print_r($book); //is it each indervidual book array with 4 elements
echo '<tr><td>'.$book[0].'</td><td>'.$book[1].'</td><td>'.$book[2].'</td><td>'.$book[3].'</td></tr>';
}
echo '</table>';

how to add value in existing .txt file when hit radio

For a simple voting system i use a .txt file in which the values are stored.
This is the array of options:
$quickpolloptions = ['Mozilla', 'Chrome', 'Opera', 'IE', 'Safari'];
This is the form:
<form method="post" id="quickpoll">
<table>
<?php
foreach ($quickpolloptions as $key => $value) {
echo "<tr>";
echo "<td>";
echo "<label>$value</label>";
echo "</td>";
echo "<td>";
echo "<input type='radio' name='radiovote' value='$key'><br>";
echo "</td>";
echo "</tr>";
}
?>
</table>
<input type="submit" value="Submit">
</form>
This is how i try to add the values in the .txt file (vote_result.txt)
$result_file = "data/vote_result.txt";
if (file_exists($result_file)) {
$results = explode(',', file_get_contents('vote_result.txt'));
} else {
// start with zeros if you don't have a file yet
$results = array_fill(0, count($quickpolloptions), 0);
}
if (isset($_POST['radiovote'])) {
$results[$_POST['radiovote']]++;
file_put_contents('data/vote_result.txt', implode(',', $results));
}
per example: when choosing the second radio, the content of vote_result.txt looks like this: 0,1,0,0,0 This is correct. But when i vote again, lets say i chosse the 3rd radio, he overwrites the .txt file and creates this: ,1. And it should be this: 0,1,1,0,0
What i am doing wrong?
personally I would use serialize / unserialize for such tasks. You can save an array into a txt file and read it back + change it whenever you like, example:
<?php
//initial array for a new file:
$quickpolloptions = [
'Mozilla' => 0,
'Chrome' => 0,
'Opera' => 0,
'IE' => 0,
'Safari' => 0
];
$votefile = "votes.txt";
//init the file:
if(!file_exists($votefile)){
file_put_contents($votefile, serialize($quickpolloptions));
}
//read the file and convert it back to an array:
$data = unserialize(file_get_contents($votefile));
//example of adding a vote for Mozilla:
$data['Mozilla']++;
//save back the file:
file_put_contents($votefile, serialize($data));
print_r($data);
Check below code gives same output as you want.......
<?php
$quickpolloptions = ['Mozilla', 'Chrome', 'Opera', 'IE', 'Safari'];
$result_file = "vote_result.txt";
if (file_exists($result_file)) {
$results = explode(',', file_get_contents('vote_result.txt'));
} else {
// start with zeros if you don't have a file yet
$results = array_fill(0, count($quickpolloptions), 0);
}
if (isset($_POST['radiovote'])) {
$results[$_POST['radiovote']]++;
file_put_contents('vote_result.txt', implode(',', $results));
}
?>
<form method="post" id="quickpoll">
<table>
<?php
foreach ($quickpolloptions as $key => $value) {
echo "<tr>";
echo "<td>";
echo "<label>$value</label>";
echo "</td>";
echo "<td>";
echo "<input type='radio' name='radiovote' value='$key'><br>";
echo "</td>";
echo "</tr>";
}
?>
</table>
<input type="submit" value="Submit">
</form

Generating a list from a text file in PHP

I am attempting to create an ordered list from a text file. As my code currently stands, it modifys the original text file with the input all on the same line(list number). e.g if I input "mercury" it will come out as 1. mercury, but if I input "venus", it will appear as 1.mercuryvenus
I am trying to get it to work so that if I input some text such as "mercury" and hit the submit button, it will appear as
1. mercury. If I input some more text such as "venus", it will appear as 2. venus, all in ordered list format. I assume that explode may be used for this, but I am unsure of how to implement this properly. Another option would be to create a new text file for each input if that were to be more efficient.
echo "<form method='post'>
<label>Enter some text</label><br>
<textarea name='textbox' cols='60' rows='5' required></textarea>
<br>
<input type='submit' name='submit' value='Submit'/>
<input type='hidden' name='step' value=''/>
</form>";
echo "<section>";
echo "<h3>Current tasks</h3>";
$text = ("text.txt");
$extract = (isset($_POST['textbox']) ? $_POST['textbox'] : null);
$file = fopen($text,"a");
fwrite($file,$extract);
fread($file,filesize("text.txt"));
fclose($file); #Not sure where this should really go
$c = array(file_get_contents('text.txt'));
$x = explode(" ",$c); #Could be wrong format
echo "<ol>";
foreach($c as $r) {
echo "<li>" . $r. "</li>", "<br>";
}
echo "</ol>";
echo "</section>";
Here is the solution
echo "<section>";
echo "<h3>Current tasks</h3>";
$text = "text.txt";
$extract = (isset($_POST['textbox']) ? $_POST['textbox'] : null);
$file = fopen($text,"a+");
fwrite($file," ".$extract);
#fread($file,filesize("$text"));
$x = explode(" ",file_get_contents($text));
if(isset($_POST['submit'])) {
echo "<ol>";
foreach ($x as $r) {
echo "<li>" . $r . "</li>", "<br>";
}
echo "</ol>";
echo "</section>"
First, the "a" in fopen($text,"a") means append. Which means if you already have the text "mercury" in your file and your run your program again with "venus", you will be appending "venus" on the end of "mercury" to get "mercuryvenus". If you want a space between the two, you will have to add it when your write it to file: fwrite($file, " ".$extract);
Second, you do $x = explode(... and then do not use $x in your foreach statement. Use $x instead of $c in your foreach.

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);

Outputting PHP into an HTML table

I want to put my outputted PHP into a table but it doesn't like it...
The layout I want is like this
ROW - Desctiption URL
ROW2- Meta Description
And it needs to keep this same layout even when I enter more then one URL.
What happens now is that when I input lots of urls it puts all of the same parts into the same cell.. How can I change this?
Sorry its hard to explain...
Here is the code:
<?php
ini_set( "display_errors", 0);
//make the array
$TAarray = explode("\n", strip_tags($_POST['TAData']));
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
echo '<tr>';
echo (isset($tags['description']))?"<tr><td>Description($line)</td> </tr>".$tags['description']:"<tr><td>Description($line)</td></tr><tr><td>No Meta Description</td></tr>.";
echo '</tr>';
}
?>
You've got some awkward HTML there.. Try doing it like this:
//start the table
echo "<table>";
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
//start a new row in the table
echo '<tr>';
if(isset($tags['description'])){
//add two cells to the table.
echo "<td>Description($line)</td>";
echo "<td>{$tags['description']}</td>";
} else {
echo "<td>Description($line)</td>"
echo "<td>No Meta Description</td>";
}
echo '</tr>';
}
echo "</table>";
//make the array
$data='http://stackoverflow.com
http://ebay.com/';
$TAarray = explode("\n", strip_tags($data));
echo "<table>";
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
echo '<tr>';
if(isset($tags['description'])){
echo "<tr><td>Description($line):".$tags['description']:" </td> "; else{
"</tr><tr><td>Description($line)</td></tr><tr><td>No Meta Description</td></tr>.";
echo '</tr>';
}
}
echo "</table>";

Categories