Mechanism to display JSON array in checkboxes - php

I used the JSON to create an array multidimensional. Now my problem is how to make groups of checkboxes (into tables or in anything to make possible separating them, by horizontal bars for example).
This is a example of the lines of the file:
{"id": "v0", "namegroup": "Table rules create OR insert", "rule": "All classes give origin to a table.", "value": 0}
And this is how I create the array:
<?php
$file = fopen("rules.txt", "r") or exit("Unable to open file!");
$arrayRules = array();
$i = 0;
while(!feof($file))
{
$line = fgets($file);
$content = json_decode(utf8_encode($line), true);
$arrayRules[$i]['id'] = $content["id"];
$arrayRules[$i][0] = utf8_decode($content["rule"]);
$arrayRules[$i]['namegroup'] = $content["namegroup"];
$arrayRules[$i][1] = $content["value"];
$i = $i + 1;
}
fclose($file);
?>
And this is how I create the checkboxes:
echo "<input name=\"regra[]\" value=\"" . $arrayRules[$i]["id"] . "\" type=\"checkbox\" /> " . $arrayRules[$i][0] . "<br/> " ;
Remember that the user can edit the name of the group and all the other points.
As you can notice, my problem is not how to echo checkbox, but how will be the mechanism with the purpose of creating and organize the checkboxes by groups.
UPDATE1
For now I have this:
for($i=0; $i < count($arrayRules); $i++)
{
if ($arrayRules[$i]['idgroup'] == 1)
{
if ($arrayRules[$i][1] == 1)
echo "<input name=\"regra[]\" value=\"" . $arrayRules[$i]["id"] . "\" type=\"checkbox\" checked onclick=\"this.checked='checked'\"/> " . $arrayRules[$i][0] . "<br/> " ;
if ($arrayRules[$i][1] == 0)
echo "<input name=\"regra[]\" value=\"" . $arrayRules[$i]["id"] . "\" type=\"checkbox\" /> " . $arrayRules[$i][0] . "<br/> " ;
}
}
?>
the problem is that in if ($arrayRules[$i]['idgroup'] == 1) should not be the 1 but should be a variable or something that when every time it finds a new or a diferent name in the file on idgroup it add or create a new table/group of check-boxes.

Add group_id param to your json objects and resort all like
$arrayRules[$group_id][$i]
after, you can do something like:
foreach($arrayRules as $group_id=>$objects) {
// start group html
foreach($objects as $i=>$params) {
echo "<input name=\"regra[]\" value=\"" . $params[$i]["id"] . "\" type=\"checkbox\" /> " . $params[$i][0] . "<br/> " ;
}
// end group html
}

Related

Php submit form checkbox with checked box

I have a db where read all information I read a optino and the stato 1 is confirmed and 0 not... I create a table where anyone can update, check or remove check and after the submit I update all data but in the submit I see only the "checked"... the other not..
$c_row = current($row);
if ($y > 1) {
echo "<form name=salvo method=post action='dettaglio.php?tipo=1'>";
$id = substr($c_row,0,strpos($c_row, '|'));
$stato = substr($c_row,strpos($c_row, '|')+1,1);
echo "<td class='tg-dett' align=center>";
if ($stato == 1) {
echo "<input type='checkbox' name='chkColor[]' value='$c_row' checked>";
} else {
echo "<input type='checkbox' name='chkColor[]' value='$c_row' >";
}
echo "</td>";
for($i = 0; $i < count($_POST["chkColor"]); $i++)
{
if(trim($_POST["chkColor"][$i]) != "") {
echo "chkColor $i = ".$_POST["chkColor"][$i]."<br>";
}
}
}
the output is only checked, If anyone remove a check don't appear to output
You can either check on the values after posting it on being empty or not set. Or you can use the hidden input trick like so:
<input type='hidden' name='chkColor[' . $row["id"] . ']' value='0'><input type='checkbox' name='chkColor[' . $row["id"] . ']' checked>
This way it will post all boxes but will add a different value to determine which is on and which is not on.

Capture the answers from form within while loop

I want to capture answers from forms within a big loop and then update the results into database. I am not sure how to do that, I have made a sample code as follows, and want to for each Save button save each question results. Say we have 5 questions, when I click save botton 1, save answers for question 1; when click save button , save answers for question 2..
Thanks very very much, this drove me crazy.....
<?php
$x=1;
$output="";
while($x<=5){
$output .= "<form action='index.php' id='" . $x . "' method='POST'>";
$output .="<h2>Question" . $x . "</h2>";
$output .= "<h3>selection</h3>";
$output .= "<ul><li><input type='radio' name='selection" . $x . "' value='1'>1</li>";
$output .= "<li><input type='radio' name='selection" . $x . "' value='2'>2</li>";
$output .= "<li><input type='radio' name='selection" . $x . "' value='3'>3</li></ul>";
$output .= "<h3>choice</h3>";
$output .= "<ul><li><input type='radio' name='choice" . $x . "' value='a'>a</li>";
$output .= "<li><input type='radio' name='choice" . $x . "' value='b'>b</li></ul>";
$output .= "<p><textarea rows='4' cols='50' name='commentory" . $x . "' form='usrform' placeholder='Enter text here...'></textarea></p>";
$output .= "<input type='submit' name='saveResult" . $x . "' value='Save'>";
$output .= "</form>";
$output .="<br>";
$x++;
}
echo $output;
if(isset($_POST['saveResult' .$x])){
$selection = $_POST['selection' . $x];
$choice = $_POST['choice' . $x];
$commentory = $_POST['commentory' . $x];
$result=$selection . $choice . $commentory;
echo "<script>alert($result])</script>";
// This part just a sample part as I dont know how to capture the results
}
?>
In your current file, you could change the first line in the while loop to this:
$output .= "<form action='index.php?question=" . $x . "' id='" . $x . "' method='POST'>";
What this does is sends a GET request with a number, from 1-5, based on what question was submitted. You can then do something like this to differentiate between your five (or however many) questions:
$questionNumber = $_GET['question']; // The ?question= parameter sent in the URL
if($questionNumber == 1) {
// Question 1 logic here
} else if($questionNumber == 2) {
// Question 2 logic here
} ...
Or do the same thing using a switch statement:
switch($questionNumber) {
case 1:
// Question 1 logic here
break;
...
}

Format text to fit in columns in Excel

I have this block of text in an array:
"Stefan Olsson"
"Kungsvägen"
"Skolgatan"
xxxx-xx-xx
0735xxxxxx,
"Pär Davidsson"
"Skolgatan"
"Myntvägen"
xxxx-xx-xx
0709xxxxxx,
I parse this type of content to an CSV-file, for later usage in Excel. However, I want to fromat this text to fit in different columns in excell. So, when I open the CSV-file in Execel, I want the name to be in one column, the address in the column besides etcetc. How can I accomplish this? Should I use PHPExcel? Or could it be done with plain old PHP?
Here is my PHP-code
$gatunamn = $_POST['gata'];
$ort = $_POST['omrade'];
$csv_data = array();
$newSpider->fetchPage($gatunamn, $ort, $offset=0);
$obj = json_decode($newSpider->html);
echo "<div id='rightcontent'><table id='one-column-emphasis'>";
echo "<th><input type='checkbox' name='csv_all' id='csv_all'></th><th>Namn</th><th>Adress</th><th>Adress2</th><th>Adress3</th><th>Personnummer</th><th>Telefonnummer</th><th>Telefonnummer2</th>";
$antal_sidor = round($obj->search->wp->totalHits / $obj->search->wp->pageSize);
echo "<td></td>";
foreach($obj->search->wp->features as $fish) //Loopar ut 50st (pageSize)
{
echo "<tr>";
echo "<td><input type='checkbox' value='csv' class='csv'></td>";
echo "<td>" . $fish->name . "</td>";
$csv_data[] .= utf8_decode($fish->name);
foreach($fish->addresses as $ad)
{
echo "<td>" . $ad->label . " " . $ad->postcode . " " . $ad->area . "</td>";
$csv_data[] .= utf8_decode($ad->label . " " . $ad->postcode . " " . $ad->area);
}
if(!empty($fish->dateOfBirth))
{
$convert_date = substr($fish->dateOfBirth, 0, -3); //Gör om datum från timestamp
echo "<td>" . date("Y-m-d", $convert_date) . "</td>";
$convert_datee = date("Y-m-d", $convert_date);
$csv_data[] .= $convert_datee;
}
if(!empty($fish->phoneNumbers))
{
foreach($fish->phoneNumbers as $ph)
{
echo "<td>" . $ph . "</td>";
$csv_data[] .= $ph . ",";
}
}
echo "</tr>";
}
echo "</table>";
$j = 0;
for($i = 1; $i <= $antal_sidor; $i++)
{
echo "<a href='curl2.php?gatunamn=$gatunamn&ort=$ort&offset=$j'>" . $i . "</a> ";
$j += 100;
}
echo "</div>";
echo "<div id='debug'><pre>";
var_dump($csv_data);
echo "</pre></div>";
}
if(isset($_POST['export']))
{
$fp = fopen("eniroo.csv","w");
foreach(explode(",", implode("\n",$csv_data)) as $rad) {
fputcsv($fp, array(implode(',', str_getcsv($rad, "\n"))));
}
echo "<div id='csv_info'>";
echo "<a href='eniro.csv'>Hämta CSV-fil</a>";
echo "</div>";
}
// Restructure the original array into rows
$myDataArray = array_chunk($myDataArray, 5);
// Then write to CSV
$fp = fopen('file.csv', 'w');
foreach($myDataArray as $dataRow) {
fputcsv($fh, $dataRow);
}
fclose($fh)

How to combine a PHP variable and $_REQUEST?

I am retrieving data from a dynamic form. For that I have counted the number of elements on the form and made each input have a unique name, using the counter variable, eg:
echo "<input type='hidden' name='itemid" . $i . "' value='" . $row['itemid'] . "' />";
On the relieving page I need to modify $_REQUEST[] to include its own counter variable, eg:
while($x <= $counter){
$itemid = trim($_REQUEST['itemid" . $x . "']);
$x = $x + 1;
};
Does anyone know the correct way of combining the $_REQUEST and $x variable?
$itemid = trim($_REQUEST['itemid" . $x . "']);
should be
$itemid = trim($_REQUEST['itemid' . $x]);
A better way to do this would be to use arrays. Then you don't need to use a counter to keep track of where you are:
echo "<input type='hidden' name='itemid[]' value='" . $row['itemid'] . "' />";
PHP:
foreach ($_REQUEST['itemid'] as $item) {
// do stuff
}

How do i email data from a form built with a while loop?

As part of a project I have a form in which our clients can edit a list of the keywords in which we work on as part of their SEO.
This is the code I use to display the keywords we have for them on our database
<?php
$c = true;
while($row = mysql_fetch_array($result))
{
$counter++;
echo "<div" .(($c = !$c)?' class="right"':'') . ">";
echo "<label for='keyword". $counter ."'>",
"<strong>Keyword " . $counter . " </strong></label>";
echo "<input type='text' name='keyword". $counter .
"' id='keyword". $counter ."' value='". $row['keyword'] . "' />";
echo "</div>";
}
?>
What I don't know what do do is collect the data when the form is submitted into an email.
I have the PHP mail bit ready but struggling on this a bit.
Any help?
I'd recommend changing the code to this:
<?php
$c = true;
while($row = mysql_fetch_array($result))
{
$counter++;
echo "<div" .(($c = !$c)?' class="right"':'') . ">";
echo "<label for='keyword". $counter ."'>",
"<strong>Keyword " . $counter . " </strong></label>";
echo "<input type='text' name='keyword[]' id='keyword". $counter ."' value='". $row['keyword'] . "' />";
echo "</div>";
}
?>
You can then access all keywords in the target php file for your form (after submission) using $_POST['keyword'], eg
foreach($_POST['keyword'] as $key => $value) {
echo "Keyword #". $key." value: ". $value."<br />";
// or your code to build your message
}
Instead of naming the inputs like "keyword1", "keyword2", etc, just name them all "keyword[]". When the form is submitted, PHP will aggregate them all into an array.
To use the POST data (make sure your form is using POST):
<?php
$message = '<ol>';
foreach($_POST as $key => $post) {
$message .= "<li><strong>Keyword " . $key . ":</strong>";
$message .= " <span>" . $post . "</span>";
$message .= "</li>";
}
$message .= '</ol>';
// mail the message here.
?>
Brian and Ergo summary are right, but if you don't want to modify the code inside the while loop you could, at the end of that, insert an hidden input that holds the last $counter value. Then in the target php file (where you will send the email), you can load the POST fields (modifying what Stephen wrote):
<?php
$counter = (int)$_POST['counter'];
$message = '';
for($i = 1; $i <= $counter; $i++){
$key = $_POST['keyword'.$i];
$message .= "<p>";
$message .= "<strong>Keyword " . $key . " </strong></label>";
$message .= "<span> " . $post . "</span>";
$message .= "</p>";
}
// mail message here.
?>

Categories