For a simple voting system, i put the values into a .txt file.
This is the array i use:
$quickpolloptions = ['Mozilla', 'Chrome', 'Opera', 'IE', 'Safari'];
This is the form:
<form method="post" id="quickpoll">
foreach ($quickpolloptions as $key => $value) {
echo "<tr>";
echo "<td>";
echo "<label>$value</label>";
echo "</td>";
echo "<td>";
echo "<input type='checkbox' name='checkboxvote[]' value='$key'><br>";
echo "</td>";
echo "</tr>";
}
<input type="submit" value="Submit">
</form>
This is how i store the data:
$result_file = "data/vote_result.txt";
if (file_exists($result_file)) {
$results = explode(',', file_get_contents('data/vote_result.txt'));
} else {
// start with zeros if you don't have a file yet
$results = array_fill(0, count($quickpolloptions), 0);
}
// below i am trying to read each value fromn checkbox and store in .txt file
if (isset($_POST['checkboxvote'])) {
foreach ($_POST['checkboxvote'] as $checkbox) {
$results[$_POST['checkboxvote']]++;
file_put_contents('data/vote_result.txt', implode(',', $results));
}
}
So i do not succeed in the last part: to put multiple values in the txt file.
How can i do that?
Use the $checkbox variable as the key to $results when incrementing the values. Also, don't write to the file inside the loop. Just update the array and then write to the file once.
if (isset($_POST['checkboxvote'])) {
foreach ($_POST['checkboxvote'] as $checkbox) {
$results[$checkbox]++;
}
file_put_contents('data/vote_result.txt', implode(',', $results));
}
In your foreach loop you are looping over $_POST['checkboxvote'] which is correct. However $checkbox is the element.
Second, you are inserting the value into the index of $results, you need them as the data of the results so implode will combine them.
Lastly, you should call file_put_contents() outside of your foreach loop. If you call it multiple times it will appear to work correctly but it will be wasting time by overwriting your file each loop.
foreach ($_POST['checkboxvote'] as $checkbox) {
$results[] = $checkbox;
file_put_contents('data/vote_result.txt', implode(',', $results));
}
or
foreach ($_POST['checkboxvote'] as $key => $checkbox) {
$results[] = $_POST['checkboxvote'][$key];
file_put_contents('data/vote_result.txt', implode(',', $results));
}
I think $results[$_POST['checkboxvote']]++; should be $results[$checkbox]++;
Note that your implementation is susceptible to race conditions if two people vote at the same time.
You should use file locks or consider an RDBMS with transaction protection.
Example:
if (isset($_POST['checkboxvote'])) {
/* lock the file to prevent a race condition */
$file_handle = fopen($result_file, 'a+');
$locked = flock($file_handle, LOCK_EX);
/* retrieve the results now that we are locked */
$results = fgets($file_handle);
if ($results !== false) {
$results = explode(',', $results);
} else {
$results = array_fill(0, count($quickpolloptions), 0);
}
/* update the results */
foreach ($_POST['checkboxvote'] as $checkbox) {
$results[$checkbox]]++;
}
/* write them to the file and unlock */
ftruncate($file_handle, 0);
fputs($file_handle, implode(',', $results));
flock($file_handle, LOCK_UN);
fclose($file_handle);
}
I am assuming the second code block is an HTTP endpoint which you hit to save data into your vote_result.txt file.
You're getting the contents of what's currently in that file right now and assigning it to the variable $result - something which you don't need to do since you never actually return it as a response from the script.
All you need is the code that will take the POST parameter array of checkboxvote and save it as a string with commas separating the values. Something like:
if(isset($_POST['checkboxvote'])){
file_put_contents('data/vote_result.txt', implode(',', $_POST['checkboxvote']));
}
You don't need the for loop when writing to your file since implode() already breaks down your array into one string.
Now, when you POST to your script with the following parameter:
checkboxvote[]='owl'
checkboxvote[]='chicken'
checkboxvote[]='deer'
Your vote_result.txt will look like:
owl,chicken,deer
Related
I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}
I want to change the value of the $key because I have array_splice inside the loop which change the position of my values so - it mess up the value I need in a specific place.
I tried $key-- but it doesn't work.
for example when I print the $key after I do echo $key it's fine but when I echo $key just after the foreach loop I get the worng value.
Any ideas?
foreach ($cut as $key => $value) {
echo "foreach key:".$key."<br>";
if(in_array($value,$operators))
{
if($value == '||')
{
echo "found || in position:".$key."<br>";
if(($key+1<sizeof($cut)))
{
$multi = new multi;
echo "<br>"."key-1: ";
print_r($cut[$key-1]);
echo"<br>";
echo "<br>"."key+1: ";
print_r($cut[$key+1]);
echo"<br>";
$res = $multi->orex($cut[$key-1],$cut[$key+1],$numString);
$cut[$key-1]= $res;
array_splice($cut,$key,1);
array_splice($cut,$key,1);
$key--; //here trying to change the key
echo "new string:";
print_r($cut);
echo "<br>";
echo "key:".$key."<br>";
}
}
}
}
Updated
I don't think it is a good idea to change the array itself inside the foreach loop. So please crete another array and fill data into it, which will be your result array. This method works well when your array data is not big, in other words, most situations.
Origin
I don't know what do you mean. Let me give it a guess...
You want:
foreach($arr as $key=>$val){
$newkey = /* what new key do you want? */
$arr[$newkey] = $arr[$key];
unset($arr[$key]);
}
i have data from php loop foreach like this
foreach ($query->result() as $row) {
echo $row->name;
}
how to make the result show only the end data without remove others if data has same (if data have same value, hide all except the last one) like this:
*sorry bad english, this is the first time i ask here. thank you
Online Check, This is just a demo example.
See below the real example:
At first you need to use array_search for get the position of the same data, if exist then just remove it using $arr[$pos] = '';, and each and every time you need to import data into the new array called $arr and after completing fetching data you need to use a foreach loop to print them.
$arr = array();
foreach($query->result() as $row){
$pos = array_search($row->name, $arr);
if($pos !== false)
$arr[$pos] = '';
$arr[] = $row->name;
}
foreach($arr as $val){
echo $val.'<br/>';
}
Check this and let me know.
The data_seek method might help. This assumes your array is reasonable ordered to begin with.
$rowCount = 0;
$res = $query->result();
foreach($res as $row) {
if ($rowCount < $res->num_rows - 1) {
// set internal pointer to next row
$res->data_seek($rowCount + 1);
// if the row names match, print an empty string
// otherwise print the current name
$nextRow = $res->fetch_row();
if ($row->name == $nextRow->name) {
echo "";
// reset the internal pointer
$res->data_seek($rowCount);
} else {
echo $row->name;
}
} else {
echo $row->name;
}
// update the row count
$rowCount += 1;
}
I have a problem with displaying my data. I have data in the following
filter_name filter_value
Hard Drize Size 16GB
Hard Drize Size 32GB
Screen Size 7''
Screen Size 8''
And I want to present it like this.
Hard Drize Size
16GB
32GB
Screen Size
7''
8''
What I want in my php code is to check if the filter_name is in the $temp array and if it isn't then add it to $temp array so it won't cause duplicate entries. The problem I'm getting now is when I use the same data to do a second foreach inside the loop I get no data and my sql is correct. So I don't know how to out put the values. With the second foreach it only prints out the first $filter_name["filter_name"] and that all.
php:
if($stmt->rowCount() > 0)
{
$filters = "<div class=\"filters\">
<div class=\"apply-filters\">Filters</div>";
$temp = array();
$stmt->fetch(PDO::FETCH_ASSOC);
foreach($stmt as $filter_name)
{
if(!in_array($filter_name["filter_name"], $temp))
{
$temp[] = $filter_name["filter_name"];
$filters .= "<div class=\"filter-header\">".$filter_name["filter_name"]."</div>";
//second loop here doesn't work with the same data.
// test if filter_name["filter_name"] == second loop second_loop["filter_name"]
// ten write out second_loop["filter_value"] e.g.
foreach($stmt as $filter_value)
{
if($filter_name["filter_name"] == $filter_value["filter_name"])
{
$filters .= $filter_value["filter_value"] ."<br />";
}
}
}
}
$filters .= "</div>";
}
First, do a var_dump of $stmt before the first and second foreach to look at it's form. Perhaps it's not formatted the way you think?
Why don't you loop over $stmt once and in that loop print $stmt['filter_name'] and $stmt['filter_value']? Now you loop $stmt one "extra" time for each iteration of the first foreach. Instead just do a foreach($stmt as $filter) and $filter, being a associative array, should contain filter_name and filter_value for each entry.
You could then move the actual printing outside of the foreach and only construct your array in the loop that should look something like
array("Hard Drive Size" => array("16GB", "32GB"), "Screen Size" => array("7''", "8''"));
Then you could traverse that data structure using
foreach($myArray as $filter_name => $filter_values)
{
// Print filter name header
foreach($filter_values as $filter_value)
{
// print each value of the specific filter
}
}
To build the presented structure you could do something like
...
$filters = array();
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $filter)
{
$filters[$filter['filter_name']][] = $filter['filter_value'];
}
...
Then iterate the $filters structure and print it.
Update:
From your var_dump of $stmt it's clear that $stmt is not your result set. You should assign the result of $stmt->fetch to something. Like $result = $stmt->fetch(PDO::FETCH_ASSOC) and then iterate over $result.
Check
http://php.net/manual/en/pdostatement.fetch.php
http://php.net/manual/en/pdostatement.fetchall.php
i slightly modified your code to fit your needs:
$temp = array();
foreach($stmt as $filter_name)
{
if(!in_array($filter_name["filter_name"], $temp))
{
echo '<b>' . $filter_name['filter_name'] . '</b><br>';
$temp[] = $filter_name["filter_name"];
foreach($stmt as $filter_value)
{
if($filter_name["filter_name"] == $filter_value["filter_name"])
{
echo $filter_value['filter_value'] . '<br>';
}
}
}
}
you can check a working sample here -> http://codepad.viper-7.com/aFD079
You are missing $ before filter_value.
Change
foreach($stmt as filter_value)
To
foreach($stmt as $filter_value)
$stmt->fetch(PDO::FETCH_ASSOC);
foreach($stmt as $filter_name)
may be (i am not sure)
$aaa= $stmt->fetch(PDO::FETCH_ASSOC);
foreach($aaa as $filter_name)
and try
$rows = $stmt->fetch(PDO::FETCH_ASSOC);
$tmp_name='';
$html='';
foreach($rows as $row)
{
if($row['filter_name'] != $tmp_name){
$html .=$row['filter_name'];
}
$html .=$row['filter_value'];
$tmp_name=$row['filter_name'];
}
echo $html;
if($stmt->rowCount() > 0)
{
$filters = "<div class=\"filters\">
<div class=\"apply-filters\">Filters</div>";
$temp = array();
$stmt->fetch(PDO::FETCH_ASSOC);
foreach($stmt as $filter)
$temp[$filter['filter_name']][] = $filter['filter_value'];
foreach($temp as $filter_name => $filter_values)
{
$filters .= "<div class=\"filter-header\">".$filter_name."</div>";
foreach ($filter_values as $value)
$filters .= $filter_value."<br />";
}
$filters .= "</div>";
}
I need to pass a variable to a foreach loop from a mySQL result.
So I have this code:
$GetClaim = "SELECT * FROM cR_Claimants WHERE memberID = '".$memberID."' AND ParentSubmission ='".$refNumb."'";
$resultGetClaim=mysql_query($GetClaim) or die("Error select claimants: ".mysql_error());
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
$name = $rowGetClaim['Name'];
$city = $rowGetClaim['city'];
$region = $rowGetClaim['region'];
}
Now I need to pass the variable to the foreach
foreach($name as $k=>$v) {
echo $city;
echo $region;
etc..
}
The above code does not work. I think I cannot pass a variable from a mySQL loop. The problem is also tat every row I get from the database should be related to the specific $name. So obvioiusly one $name will have its own $city etc..
How do I achieve this?
Please help
You are not retrieving an array with all returned records, you are retrieving an array which contains a single record.
To get the next name (the next record), you must make another call to mysql_fetch_array.
The code you present does that implicitly by assigning $rowGetClaim within a while conditional. A failed mysql_fetch_array call would return false, which would exit the while loop.
There is absolutely no need to use the for each as you presented. Just place the echo right after the assignment (e.g.
$region = $rowGetClaim['region'];
echo $region
Either out put directly fromt eh loop or build an array and then loop through it.
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
echo $rowGetClaim['Name'];
echo $rowGetClaim['city'];
echo $rowGetClaim['region'];
}
OR
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
foreach($rowGetClaim as $k => $v{
echo $v;
}
}
OR
$names = array();
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
$names[] = $rowGetClaim;
}
foreach($names as $data){
foreach($data as $k => $v) {
echo $v;
}
}