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
Related
I need to convert JSON into a list using PHP, Tried code below but cannot make it work
$json=file_get_contents("http://feeds.mse.mk/service/FreeMSEFeeds.svc/ticker/JSON/8BA941D0-D6E6-44BD-8D8B-47FDB7A563FA");
$data = json_decode($json);
if (count($data->stand)) {
// Open the table
echo "<table>";
// Cycle through the array
foreach ($data->stand as $idx => $stand) {
// Output a row
echo "<tr>";
echo "<td>$stand->AvgPrice</td>";
echo "<td>$stand->Description </td>";
echo "</tr>";
}
// Close the table
echo "</table>";
}
And I want to show list as here (not as a table):
http://prntscr.com/no1479
your all code is right but you can use stand class that is wrong your class is GetTickerJSONResult and so change the class stand to GetTickerJSONResult.
try this modified code..
<?PHP
$set =json_decode($json);
if (count($set->GetTickerJSONResult)) {
echo "<table>";
foreach ($set->GetTickerJSONResult as $idx => $stand) {
echo "<tr>";
echo "<td>$stand->AvgPrice</td>";
echo "<td>$stand->Description </td>";
echo "</tr>";
}
echo "</table>";
}
?>
It does not work because in $data->stand there is nothing.
Hi there this is a bit hard to word so I'm trying my best to explain what is happening. Pretty much I have a form where I had a selection box. I had to fill it with the following.
<?
$PROVINCES = array("--" => "---Please Select Provinces---",
"nf"=>"Newfoundland",
"pe"=>"PrinceEdwardIsland",
"nb"=>"New Brunswick",
"ns"=>"Nova Scotia",
"qc"=>"Quebec",
"on"=>"Ontario",
"mb"=>"Manitoba",
"sk"=>"Saskatchewan",
"ab"=>"Alberta",
"bc"=>"British Columbia",
"nt"=>"Northwest Territories");?>
So I did that:
<select name = "province[]" multiple size = "12" <?if ($_SERVER['REQUEST_METHOD'] == 'POST'){if (isset($errorList['province']))
{
echo "class=\"error\"";
}}?>>
<?php foreach($PROVINCES as $key => $value) { ?>
<option value="<?php echo $key ?>"<?= (in_array($key, $_POST['province'] ) )?'selected':'';?>><?php echo $value?></option>
<?php }?>
</select>
Now the next step was to make a table of all the values in $_POST
but the problem is since the values are nf, pe, nb etc it will write those in the table and not PrinceEdwardIsland, New Brunswick, Nova Scotia.
echo '<table border="1" style="width:100%">';
foreach($_POST as $name => $out)
{
echo '<tr>';
echo '<td>';
echo '<strong>';
echo strtoupper($name);
echo '</strong>';
echo '</td>';
echo '<td>';
if (is_array($out))
{
count($_POST);
$arrayOutput = implode(", ", $out);
echo $arrayOutput;
}
else if (strlen($out) <= 0)
{
echo "---None supplied---";
}
else
{
echo $out;
}
echo '</td>';
echo '</tr>';
}
echo '</table>';
But as you can see from here we have multiple different $name from $_POST when we call it in our foreach loop.
And as you can see when I do is_array($out) I implode the array and split it out by ","'s I only need to get the full names for provinces, I had a checkbox for Status and it only has to display what the value in the checkbox was. I'm trying to figure out how I can get the $key of $PROVINCES to replace the imploded values in $_POST['province']
Hopefully I explained it well enough for people to understand.
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>";
I really don't understand why I'm getting this error or how to fix it!
Variable passed to each() is not an array or object on line-
while(list($key,$value) = each($_FILES['images']['name']))
Full code-
$max_no_img=4; // Maximum number of images value to be set here
$imgs_names = array('CV', 'Research Plan', 'Degree Transcript', 'GRE Scores');
echo "<form method=post action='' enctype='multipart/form-data'>";
echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=left>";
for($i=1; $i<=$max_no_img; $i++){
echo "<tr><td>".$imgs_names[$i-1]."</br</td><td>
<input type=file name='images[]' class='bginput'></td></tr>";
}
echo "<tr><td colspan=2 align=center><input type=submit value='Submit'></td></tr>";
echo "</form> </table>";
while(list($key,$value) = each($_FILES['images']['name']))
{
echo $key;
echo "<br>";
echo $value;
echo "<br>";
if(!empty($value)){ // this will check if any blank field is entered
$filename =rand(1,100000).$value; // filename stores the value
$filename=str_replace(" ","_",$filename);
$add = "upload/$filename"; // upload directory path is set
copy($_FILES['images']['tmp_name'][$key], $add);
echo $add;
Any ideas?
$_FILES['images']['name] is not an array, $_FILES['images'] is.
So
while (list($key, $object) = each($_FILES['images']))
{
//use $object['name'] or $object['tmp_name']
}
$_FILES['images']['name'] is not an array! It is a value inside the array.
If you want to iterate over the files, you should:
while(list($key,$value) = each($_FILES['images']) {
(...)
}
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.