How to get multiple html array contents with php - php

I have an issue using jquery to append an create more input tags, so i can collect multiple data and be treated as an array. But each time i process it with php, only one data is sent.Kindly help out.
<div class="half" id="bs_cat">
<form method="POST">
<div>
<div class="label">Create Category</div>
<div class="label" id="bs_cat1"><input type="text" class="form_element" name="bs_category[]" placeholder="Football, handball, basketball e.t.c" /></div><br />
</div>
</div>
<div class="label half center">
<input type="submit" class="button" value="Create Categorie(s)" />
<a class="button" href="#" onclick="$('#bs_cat').append('<div>'+$('#bs_cat1').html()+'Add Another Category
</div>
Here is the php i have processing it
$bs_category = $_POST['bs_category'];
$n = 0;
foreach($bs_category as $c){
if(!empty($c)){
$bs = $afrisoft->antiHacking($c);
$sQl = $afrisoft->dbcountchanges("INSERT INTO sport (bs_categories)
VALUES ('$bs')");
if($sQl > 0) $n++;
}
}
I'll appreciate any help i can get. Thanks

Try putting the name bs_category on the form itself rather than the input field

Related

writing hierarchical XML with HTML form/PHP

I am working on a project where I am seeking to provide an HTML form where users can enter values in form inputs, which would then be added to an XML file on submit.
So far, I have found examples of how to do this, but only at one level of XML data, for example a form with an input for "name" that submits to an XML file like the following:
<meals><type>breakfast</type></meals>
Or perhaps like this:
<meals>
<meal>
<type>breakfast</type>
</meal>
</meals>
I am seeking to use forms to write XML node content at an additional level, such as:
<meals>
<meal>
<type>breakfast</type>
<ingredients>
<ing>eggs</ing>
</ingredients>
</meal>
<meal>
<type>dinner</type>
<ingredients>
<ing>pork chop</ing>
</ingredients>
</meal>
</meals>
I have a form that provides for input of these elements, and a PHP script that writes them to an XML document, but I am not sure how to iterate over the nested arrays respective of their parent elements. When I submit the data above, the XML that I get is like the following:
<meals>
<meal>
<type>breakfast</type>
<ingredients>
<ing>eggs</ing>
<ing>pork chop</ing>
</ingredients>
</meal>
<meal>
<type>dinner</type>
<ingredients>
<ing>eggs</ing>
<ing>pork chop</ing>
</ingredients>
</meal>
</meals>
In other words, my PHP script creates an array of meals, and an array of ingredients, but I am wondering if there is a way to create nested arrays of meal>ingredients, or meal[i]ingredients.
Edit to add code for the HTML form and PHP script:
The HTML form:
<form>
<input name="done" value="done" type="submit">
<fieldset name="meal">
type: <input name="type[]" type="text">
<br>
Ingredients
<fieldset name="ingredients">
ing. name: <input name="ingName[]" type="text">
</fieldset>
</fieldset>
<fieldset name="meal">
type: <input name="type[]" type="text">
<br>
Ingredients
<fieldset name="ingredients">
ing. name: <input name="ingName[]" type="text">
</fieldset>
</fieldset>
</form>
There is JS that allows for adding additional meal s and ingredient inputs.
Here is the PHP script:
if(isset($_REQUEST['done']))
{$xml = new DOMDocument("1.0","UTF-8");
$xml->load("groceries4.xml");
$rootTag=$xml->getElementsByTagName("groceries")->item(0);
$mealTypes=$_REQUEST['type'];
foreach($mealTypes as $mt)
{$mealTag=$xml->createElement("meal");
$mealType=$xml->createElement("type",$mt);
$mealTag->appendChild($mealType);
$ingrsTag=$xml->createElement("ingredients");
$mealTag->appendChild($ingrsTag);
$mealIngs=$_REQUEST['ingName'];
foreach($mealIngs as $mi)
{$ingTag=$xml->createElement("ing",$mi);
$ingrsTag->appendChild($ingTag);};
$rootTag->appendChild($mealTag);};
$xml->save("groceries4.xml");
}
?>
Many developers overlook how they name their input fields, particularly when it comes to related information.
In this particular case, it can make your life easier when you build the XML.
HTML
<form method="post">
<!-- meal #1 -->
<div class="meal">
<h1>Meal #1</h1>
<h2>Type</h2>
<input type="text" name="meals[0][type]" value="m1 t" />
<div class="ingredients">
<h2>Ingredients</h2>
<div class="ingredient">
<h3>Ingredient #1</h3>
<input type="text" name="meals[0][ingredients][0][inc]" value="m1 ing1" />
</div>
<div class="ingredient">
<h3>Ingredient #2</h3>
<input type="text" name="meals[0][ingredients][1][inc]" value="m1 ing2" />
</div>
</div>
</div>
<!-- meal #2 -->
<div class="meal">
<h1>Meal #2</h1>
<h2>Type</h2>
<input type="text" name="meals[1][type]" value="m2 t" />
<div class="ingredients">
<h2>Ingredients</h2>
<div class="ingredient">
<h3>Ingredient #1</h3>
<input type="text" name="meals[1][ingredients][0][inc]" value="m2 ing1" />
</div>
<div class="ingredient">
<h3>Ingredient #2</h3>
<input type="text" name="meals[1][ingredients][1][inc]" value="m2 ing2" />
</div>
</div>
</div>
<!-- keep going -->
<input type="submit" value="Save" />
</form>
Upon submission, it makes it easier to loop
PHP
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$doc = new DOMDocument('1.0', 'UTF-8');
$xmlEl = $doc->createElement("xml");
$xmlEl = $doc->appendChild($xmlEl);
// add meals
if (isset($_POST['meals'])) {
$mealsEl = $doc->createElement("meals");
$mealsEl = $xmlEl->appendChild($mealsEl);
foreach ($_POST['meals'] as $meal) {
// add meal
$mealEl = $doc->createElement("meal");
$mealEl = $mealsEl->appendChild($mealEl);
// add meal type
if (isset($meal['type'])) {
$mealEl->appendChild($doc->createElement("type", $meal['type']));
}
// add meal ingredients
if (isset($meal['ingredients'])) {
$ingredientsEl = $doc->createElement("ingredients");
$ingredientsEl = $mealEl->appendChild($ingredientsEl);
foreach ($meal['ingredients'] as $ingredient) {
// add ingredient
$ingredientEl = $doc->createElement("ingredient");
$ingredientEl = $ingredientsEl->appendChild($ingredientEl);
// add inc
if (isset($ingredient['inc'])) {
$ingredientEl->appendChild($doc->createElement("inc", $ingredient['inc']));
}
}
}
}
}
$doc->save("meals.xml");
}
?>
Though if you are clever enough, you can probably recursively build the XML as there is a pattern somewhere - unfortunately, I am not.
This answer is based off this answer.

how to get the submit button value which is in while loop using post method

Input field inside a while condition i'm displaying the tab in which tab values are fetched from table red_digid_info
<form method="POST" action="" id="form_isp_status" onsubmit="submit_isp_status('form_isp_status');"">
<div class="row">
<label for="fromdate" class="col-sm-1 control-label"> FROM DATE </label>
<label for="todate" class="col-sm-1 control-label" style="margin-left: 4cm;"> TO DATE </label>
</div>
<div class="row">
<div class="col-sm-1">
<div class="input-group">
<input type="text" class="form-control" id="fromdatepicker" name="fromdate" placeholder="yyyy-mm-dd" style="width:200px;height:33px;">
<span class="input-group-addon"><i class='glyphicon glyphicon-calendar'></i></span>
</div>
</div>
<div class="col-sm-1" style="margin-left:4cm">
<div class="input-group">
<input type="text" class="form-control" id="todatepicker" name="todate" placeholder="yyyy-mm-dd" style="width:200px;height:33px;">
<span class="input-group-addon"><i class='glyphicon glyphicon-calendar'></i></span>
</div>
</div>
<div class="col-sm-offset-2 col-sm-2">
<input type="submit" value="ISP Status" class='btn btn-purple btn-rounded w-md m-b-5' name="isp_button">
<input type="hidden" value="1" name="pointer">
<button type="button" class="btn btn-pink btn-rounded w-md m-b-5" onclick="resetforms('form_isp_status')">Reset</button>
</div>
</div>
<div class="row">
<label for="isp" class="col-sm-1 control-label"> SELECT ISP</label>
</div><div class="row">
<div class="tab">
<?php
$isp_tab = mysql_query("SELECT DISTINCT(`isp`) FROM `red_dgid_info`");
while ($result = mysql_fetch_array($isp_tab)) {
$isp_value = $result[0];
echo '<input class="tablinks ion-social-rss" type="submit" name="isp_value[]" value="'.$isp_value.'">';
//echo '<input type="hidden" name="isp_hidden_value[]" value="'.$isp_value.'">';
}
?>
</div>
</div></form>
if i click any one value of a tab i ve to display the tab content so i need the value of submit button in php post method
if($_REQUEST['pointer'] ==1)
{
var_dump($_POST);
//-------status criteria given---------------------//
//-----------isp tab submiited--------------//
if(isset($_POST['isp_value']))
{
print_r($_POST['isp_value']);
$isp=$_POST['isp_value'];
}
//------------------end----------------------//
//----------hidden value array--------------//
/*$data = $_POST['isp_hidden_value'];
foreach($data as $isp)
{
echo "isp_hidden =".$isp;
}
//---------------another way----------------//
$isp_hidden = $_POST['isp_hidden_value'][$isp];*/
//--------------end------------------------//
$date= date("Y-m-d");;
$fromdatepicker =$_POST['fromdate'];
$todatepicker =$_POST['todate'];
exit;
}
if(isset($_POST['isp_value'])) //this if condition fails isp_value is not set don't know the reason and solution for it
submit function
function submit_isp_status(formId) {
if($("#"+formId).valid() == true) {
$.ajax({
type: 'POST',
url: 'webxstatus.php', //same page
data: $("#"+formId).serialize(),
success: function(data) {
..........
}
});
}
}
I'm stuck with this for past 2 days anyone help me to solve this.
you need to change your input name to array like this isp_value[] so only you can get the value which submit button you clicked otherwise you will get last value only .
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value[]' value='$isp_value'></input>"
PHP :
print_r($_POST['isp_value']);
And also minor single quotes problem in your isp_hidden_value
echo '<input type="hidden" name="isp_hidden_value[]" value="'.$isp_value.'">';
note:
if you need currently clicked submit button value means . don't use hidden field it will collect all values . just insert the value in submit button it will collect only curently clicked element value only as a array
Try this example :
<?php
if(isset($_POST['xyz']))
{
print_r($_POST);
}
?>
<form action="" method="post">
<input type="submit" name="xyz[]" value="1" >
<input type="submit" name="xyz[]" value="2" >
</form>
<?php $isp_tab=mysql_query("select distinct(isp) from red_dgid_info");
while($result=mysql_fetch_array($isp_tab))
{
echo'<form method="POST" action="" id="form_isp_status" onsubmit="submit_isp_status('form_isp_status');">';
$isp_value =$result[0];
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value' value='$isp_value'></input>";
echo '<input type="hidden" name="isp_hidden_value" value='$isp_value'>';
echo'</form>';
}?>
put form inside while loop
while($result=mysql_fetch_array($isp_tab))
{
$isp_value =$result[0];
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value' value='$isp_value'></input>";
echo '<input type="hidden" name="isp_hidden_value[]" value='$isp_value'>';
}?>
$data =$_POST['isp_hidden_value'];
foreach($data as $isp)
{
echo "isp_hidden"=$isp;
}
Use input field 'isp_hidden_value' as array and fetch values using foreach
You need to do some changes in your code, and after that i hope it will work perfectly:
Change hidden field
from:
echo '<input type="hidden" name="isp_hidden_value" value="$isp_value">';
to:
echo "<input type='hidden' name='isp_hidden_value[$isp_value]' value='" . $isp_value . "'>";
In the post method change value assignment of hidden field
from:
$isp_hidden = $_POST['isp_hidden_value'];
to:
$isp_hidden = $_POST['isp_hidden_value'][$isp];
Rest should work fine.
Logic behind this change is to use array when using same name for multiple input types. Here you are using a flat variable which will hold only one value, which will get assigned at the end. If you use array it will hold multiple values and allows you to get your desired result.
You don't need a hidden field for this. A button with a name should send it's value.
<?php
var_dump($_POST);
?>
<form method="POST" action="">
<div class="row">
<div class="tab">
<input type="submit" name="button" value="test1">
<input type="submit" name="button" value="test2">
</div>
</div> </form>
Will tell me that $_POST['button'] is either test1 or test2
Which means that the following should work
<form method="POST" action="" id="form_isp_status" onsubmit="submit_isp_status('form_isp_status');"">
<div class="row">
<div class="tab">
<?php $isp_tab=mysql_query("select distinct(isp) from red_dgid_info");
while($result=mysql_fetch_array($isp_tab))
{
$isp_value =$result[0];
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value' value='$isp_value'>";
// note: input is a empty tag, meaning that it is not to be closed using </input> but by using />, which
// is only relevant for XHTML
}?>
</div>
</div> </form>
Edit:
On the server side the only thing you have to do is use the value of $_POST['isp_value'].
var_dump($_POST); // only to check the POST variable during debugging
if (isset($_POST['isp_value'])) { // Possibly not needed if there are no other submit buttons in the from, but good practice to check if something exists
// do something using $_POST['isp_value']
}
As a sidenote: mysql_* has been deprecated in PHP 5.5.0 and been removed in PHP 7.0. It is recommended to either use MySQLi or PDO instead

How to add up value via function - PHP

I am trying to create a function that add up number to a given variable each time a button was click.
I have 4 buttons: farm, cave, house, casino
So what I am trying to achieve here is I need to send the random numbers generated by the buttons to a variable that will add up all of the SCORE on the "YOUR GOLD" section. So let's say I click the farm and the cave button so there will be 20 for the cave and 15 for farm for a total of 35 gold already.
Here's my form.php
<div class="wrapper">
<div id="gold">
<form action="process-game.php" method="post" >
YOUR GOLD: <input type="hidden" name="building" value="gold"/>
</form>
</div>
<div class="farm_form">
<h2>Farm</h2>
<form action="process-game.php" method="post" >
<input type="hidden" name="building" value="farm"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
<div class="farm_form">
<h2>Cave</h2>
<form action="process-game.php" method="post">
<input type="hidden" name="building" value="cave"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
<div class="farm_form">
<h2>House</h2>
<form action="process-game.php" method="post">
<input type="hidden" name="building" value="house"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
<div class="farm_form">
<h2>Casino</h2>
<form action="process-game.php" method="post">
<input type="hidden" name="building" value="casino"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
</div>
Here's my process.php:
<?php
session_start();
if(isset($_POST['building'])){
echo earn_gold();
}
function earn_gold(){
if($_POST['building'] == "farm"){
$gold = rand(10,20);
}else if($_POST['building'] == "cave"){
$gold = rand(5,10);
}else if($_POST['building'] == "house"){
$gold = rand(2,5);
}else if($_POST['building'] == "casino"){
$gold = rand(0,50);
}
return $gold;
}
?>
Any idea how to do this?
I know, you basically wanted a solution in PHP. Still, I could not resist showing you, how easy it would be doing the same in JavaScript/jQuery. Have a look at it or simply ignore it. It is up to you ... ;-)
// define gold amounts for each button (min,max):
var finds={farm:[10,20],cave:[5,10],house:[2,5],casino:[0,50]};
$(function(){
$(':submit').click(function(){ // for all submit buttons: bind the click event to a function ...
var place=$(this).closest('div[id]').attr('id'); // get the id of the buttin's parent div
var fnd=finds[place]; // get the min/max array for the current button
with ($('#gold span')) // locate and use the <span> inside the div with id=gold
text(parseFloat(text()) // get the current value of the span (convert to float)
+fnd[0]+Math.ceil(Math.random()*(fnd[1]-fnd[0]))); // add the gold ...
});
})
div {display:inline-block; width: 120px; border:1px solid grey}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="farm_form" id="gold">
<h2>Your Gold</h2><span>0</span>
</div><br>
<div class="farm_form" id="farm">
<h2>Farm</h2><input type="submit" value="Find Gold!"/>
</div>
<div class="farm_form" id="cave">
<h2>Cave</h2><input type="submit" value="Find Gold!"/>
</div>
<div class="farm_form" id="house">
<h2>House</h2><input type="submit" value="Find Gold!"/>
</div>
<div class="farm_form" id="casino">
<h2>Casino</h2><input type="submit" value="Find Gold!"/>
</div>
If you really need it, I guess you can do it with sessions.
if (isset($_POST['building'])) {
// getting random gold
$earn_gold = earn_gold();
// adding to session called "gold"
$_SESSION['gold'] = (isset($_SESSION['gold']) ? $_SESSION['gold'] + $earn_gold : $earn_gold);
// redirect back to process page
header('Location: process.php');
exit;
}
And then outputting it like so
<div id="gold">
<form method="post" >
YOUR GOLD: <input type="hidden" name="building" value="gold"/>
<?php
// if set, outputting sessions "gold" value
if (isset($_SESSION['gold'])) echo $_SESSION['gold'];
?>
</form>
</div>
When the user click on find gold then submit a form which will add the gold to the total result. For example if the user gets 3 gold then add the gold variable.
$totalGold = 0;
when user.click button then $totalgold +3;
Have one form element and use javascript to assign onclick events to each of the butons and may be use ajax to submit the form dynamically and display the results back on same page.

Reply Comment System

Hello Everyone I am new to php and doing a project. My Problem is I am working on review page and fetching data from 3 tables using while loop.
The problem is I want to create comment reply system. I am using text area for comment in loop and showing the text area on button click but when I am click on button, each text area gets visible which I don't want. I think problem is due to while loop.
Please suggest me a proper idea.
Thank u in advance.
Php part:
<div class="feedback-list">
<!--img class="doc-img"src="img/doc-img.png" alt="tempimg" height="100" width="100"/>
<div class="feedback-header"-->
<?php
while($row1=mysql_fetch_array($result1))
{
$username1=$row1['username'];
$rtitle=$row1['reviewtitle'];
$rexperience=$row1['experience'];
echo '<div class="feedback"><img class="doc-img" src="img/doc-img.png" alt="temp img" height="100" width="100"/><div class="feedback-header">Rivew by '.$username1.'
<span class="stars" id="star1"><img src="img/stars.png"/></span>
</div>
<p> '.$rtitle.'</p><br/>
<p> '.$rexperience.'</p>
<form action="submitcomment.php" method="post" name="frms">
<!--button type="submit" onclick="showCommentBox()">Reply</button><br/-->
<input type="button" value="Reply" onclick="showCommentBox('.$row1['reviewid'].')"><br/>
<div class="hidden" id="comment">
<!--p>Comments and suggestions:<br><textarea name="comments" rows="3" cols="30" ></textarea><br><br>
<input type="submit" name="sub" value="Confirm"></p-->
</div>
</form>
<span class="read-more">Read More</span>
<span class="added-by">added on 25 March</span>
</div>';}?>
Script:
<script type="text/javascript">
function showCommentBox(x){
//alert(x);
var div=document.getElementById('comment');
div.className='visible';
document.getElementById("comment").innerHTML =
'<br/><textarea maxlength="5000" cols="30" rows="3" name="comments"></textarea>' +
'<input type="submit" name="sub" value="Confirm">';
}
</script>
ALL of your comment boxes have the same DOM ID:
<div class="hidden" id="comment">
^^^^^^^^^^^^
This is not permitted. An ID must be unique across the entire page. Because of this, getElementById() will only ever return ONE element which matches, which is generally the FIRST matching element it finds - there is no point in continuing to search for something of which only one can exist, right?
You probably want something more like
<div class="hidden" id="comment{$id}">
<button onclick="showComment($id);" >
function showComment(id) {
foo = document.getElementById('comment' + id);
}

Form / ajax / PHP issue

I am trying to make a small form that lets the user pick one element from 3 different radiobutton lists to set one element as the users active element (that will be stored to MySQL). Somehow along the way it does not work and I can not seem to figure out why, perhaps someone of you can see what I did wrong?
HTML:
<form name="activeForm1" method="post">
<fieldset data-role="controlgroup">
<div class="ui-radio">
<input type="radio" name="active" value="1" id="1">
<label for="1"></label></input>
</div>
<div class="ui-radio">
<input type="radio" name="active" value="2" id="2">
<label for="2"></label></input>
</div>
<div class="ui-radio">
<input type="radio" name="active" value="3" id="3">
<label for="3"></label></input>
</div>
</fieldset>
<div data-role="footer">
<input type="submit" href="#" onclick="setActive(1)"/>
</div>
</form>
JavaScript / Ajax call
function setActive(formid)
{
$.ajax(
{
type:'POST',
url:'active.php',
data:$('#activeForm'+formid).serialize(),
success:function(response)
{
}
}
);
}
PHP code:
session_start();
include('connectToDb.php');
$id = $_SESSION['id'];
if (isset($_POST['active']))
{
$formValue = $_POST['active'];
mail('my#mail.com','Test',$formValue,'From: dummy#mail.com');
mysql_query(/* UPDATE MySQL */);
header("Location: main.php");
}
else
{
mail('my#mail.com','Test','No data recieved!','From: dummy#mail.com');
}
So it works up until the if (isset($_POST['active'])) but then mails me that no data was recieved. I already have 2 similar forms on the same page and they are way bigger and has no problems running. Can't figure out what I did wrong here.
Wrong code :
data:$('#activeForm'+formid).serialize(),
#activeForm is not an id, it is the name of the form tag,
Correct the form tag to,
<form name="activeForm1" id="activeForm1" method="post">
Replace following line
data:$('#activeForm'+formid).serialize(),
with
data: $('form[name="activeForm'+formid+'"]').serialize(),
change
<input type="submit" href="#" onclick="setActive(1)"/>
to
<input type="button" href="#" onclick="setActive(1)"/>
and then it should work

Categories