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.
Related
I'm having an issue with the code below, I want to test a user's input against values in a text file. The output of the code works only for the last element of the array (each value of the text file is stored as an element of an array) which succeeds in correctly comparing the input against the array element, however when entering any other element in the array, no 'match' is being made. I want all values to be numeric and only one same value to exist, if more than one, output an error. Thanks guys :)
array.txt has the following contents
11111
22222
33333
44444
PHP:
<?PHP
if (isset($_REQUEST['attempt'])) {
$users = file('C:/wamp/www/php/comparision/array.txt');
$input = $_POST['input'];
print "Results:";
print '<br></br>';
$x = count($users);
print '<br></br>';
print '<br></br>';
$i = 0;
while ($i < $x) {
print $users[$i];
print $input;
$truevar = NULL;
$arrayelement = $users[$i];
if ($input == $arrayelement) {
print '<p>';
echo " It is in the array";
print '</p>';
$truevar = $truevar + 1;
}
else if ($input != $arrayelement) {
print '<p>';
echo " Nope";
print '<p>';
}
print '<br></br>';
$i = $i + 1;
}
//Check entries
if ($truevar > 1) {
print '<br></br>';
echo "Multiple entries";
}
else if ($truevar == 1) {
print '<br></br>';
echo "Comparison success";
}
else if ($truevar < 1) {
print '<br></br>';
echo "Comparison not successfull";
}
}
?>
<p>Please enter data</p><br></br>
<form action="compare.php?attempt" method="post"/>
<input type="text" name="input" size="15" value="" />
<input type="submit" name="carddata" value="Submit"/>
</form>
Use:
$users = file('C:/wamp/www/php/comparision/array.txt', FILE_IGNORE_NEW_LINES);
Without that option, the newlines that separate the lines in the file are included in the values in $users, so the comparisons fail.
The problem seems that you set $truevar = NULL; inside the while loop. Like this, the variable always gets reset to NULL with every loop.
You should be fine if you move the $truevar = NULL above the while-line
I am trying to read images stored in the directory in PHP by getting only part of its name. The images are named as follows,
AT-1410f1654.jpg
AT-1410_1655.jpg
AT-1410_1656.jpg
AT-1410_1657.jpg
AT-1410_1658.jpg
AT-1410_1659.jpg
I have tried the following code below but it does not work even if I use the PHP substr() method but it also did not work,
$dbImage=$row["pref"];
$imageName=$dbImage;
$extension=".jpg";
$filename=$imageName.$extension;
echo "$filename+<img src='proppics/$filename'>";
Any ideas on how this could be done
The Full Code
$limit=10;
$con=mysql_connect("localhost","root","");
mysql_select_db("movedb") or die("Unable to select database");
$query="select * FROM properties where `name`='Beata Grande 1' & `catergory`='Villas'& `price`=202800 & `area`='Arenas'& `bedrooms`=2 & `region`='Axarquia'";
$numresults=mysql_query($query,$con);
$numrows=mysql_num_rows($numresults);
$result = mysql_query($query) or die("Couldn't execute query");
echo "<center>";
echo "<p>You searched for: "" . $properties . ""</p>";
echo "<form name=payment action='properties_details.php'>";
echo "Results <br>";
while ($row= mysql_fetch_array($result)) {
$id=$row['id'];
$pid=$row['pref'];
// Retrieve the balance database fields
echo "<p>Property ID  ".$pid;
echo "<br> <p> Name  ";
echo $row["name"];
echo "<br> Properties  ";
echo $row["catergory"];
echo "<br> Description  ";
// Print results
echo "<br>";
echo "<input type=submit name=btnbuy value=MoreDetails> ";
First, list all files in your dir using scandir
http://php.net/manual/en/function.scandir.php
then check for existing prefix using strpos
http://php.net/manual/en/function.strpos.php
$dir = 'propix';
$files = scandir($dir);
$prefix = '1410';
foreach($files as $file) {
if(strpos($prefix) !== FALSE) { //here you are supposed to add more...
echo $file;
}
}
How about glob?
Your question isn't clear enough to provide a more comprehensive answer
I am not 100% sure what you're trying to achieve.
But if you want to select only part of the filename either after the "_" or before for whatever reason, you could use PHPs explode() function.
In your case writing:
print explode("_", $dbImage);
Would have an output similar to this:
Array(
[0] => AT-1410
[1] => 1655.jpg
)
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);
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP: How to remove specific element from an array?
I've got an array for holding shopping basket information:
session_start();
$items = $_SESSION['items'];
$values = $_SESSION['values'];
if (isset($_POST['addtobasket']))
{
$items[] = $_POST['item'];
$values[] = $_POST['value'];
$_SESSION['items'] = $items;
$_SESSION['values'] = $values;
}
print("Added " . $_POST['item'] . " with value of " . $_POST['value'] . "to basket");
?>
At the checkout screen I'd like to be able the user to be able to remove items:
<?
echo "<table class='basketdisplay'>";
echo "<tr><td>Item</td><td>Price</td></tr>";
foreach($items as $key => $item)
{
echo "<tr>";
echo "<td>" . $item . "</td>";
echo "<td>£" . $values[$key] . "</td>";
echo "<td>" . $key . "</td>";
echo "</tr>";
}
echo "</table>";
?>
So instead of the last column showing the key, some form of button to remove the item at that key?
Does anyone know how I'd go about this, my php is not strong. TIA
You could use http://php.net/manual/en/function.unset.php to remove items from the array.
You'd have to figure the code though:)
unset($array[$key]);
manual
if(isset($_REQUEST['removeitem']))
{
unset($items[$_REQUEST['removeitem']]);
}
Where $_REQUEST['removeitem'] is the key of the item you want to remove. Then have your href do something like remove item.
Regarding your removal feature, you could just use a checkbox (or even a submit button) like:
echo "<td><input type=checkbox name='remove[$key]' value=1>remove</td>";
(Take care that all variables ($key) in your output also need htmlspecialchars() handling.)
Then if the basket form is submitted again, you can simply probe for elements to be removed with:
foreach ($_REQUEST["remove"] as $key) {
unset($_SESSION["items"][$key]);
}
Firstly, change this line:
echo "<td>" . $key . "</td>";
to this:
echo "<td><a href='new_php_page.php?key=$key'>Remove Item</td>";
new_php_page.php:
<?php
session_start();
$items = $_SESSION['items'];
// validate session key here - that it is an integer etc.
if (array_key_exists($_POST['key'], $_SESSION['items'])) {
unset($_SESSION['items']);
}
// redirect to cart page again
?>
An improvement would be to replace the link to a button. You could then consider using AJAX to have the item removed 'behind-the-scenes'.
Make the table a form and the final element of the row an HTML input field:
<FORM target="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<?php
echo "<table class='basketdisplay'>";
echo "<tr><td>Item</td><td>Price</td></tr>";
foreach($items as $key => $item)
{
echo "<tr>";
echo "<td>" . $item . "</td>";
echo "<td>£" . $values[$key] . "</td>";
?>
<TD>
<INPUT type="submit" name="DELETE_<?php echo $key; ?>" value="Delete"/>
</TD>
<?php
echo "</tr>";
}
echo "</table>";
?>
</FORM>
And then at the start of the script, use something like:
<?php
foreach ($_POST as $name=>$value)
{
if (preg_match('/^DELETE_(\d+)$/',$name,$matches)) //Assumes that $key is numeric
{
$keyToDelete=$matches[1];
// Put your delete code in here
}
}
?>
or something like that.
First, you must use prepared statement to prevent SQL Injection and for filtering purpose. Use PDO for this.
but i don't sure, because you don't make any link for user to delete their item.
first you must make an unique id for all item, so easy for you to remove, example :
echo 'Remove'