Pulling simplexml and parsing them into php variables. I have a form with arrays in them. I want a button outside the form that will "essentially" go to the same form but with the next array number. IE:
<?
if( $xml = simplexml_load_file('my.xml') ) {
foreach( $xml as $SAVED_EXPORT) {
$mfg = $SAVED_EXPORT->productmanufacturer;
}
}
?>
<form id="myform" method="post" action="coderdb.php">
<input type="text" value="<? echo $mfg[0] ?>" name="MFG" />
<input type="submit" />
</form>
I'd like to have a button that says NEXT that when clicked it will pull up the next array ie. $mfg[1]. I believe the page would have to be reloaded which is fine. I read somewhere I may have to use $key but have never used and I am not exactly sure its what I need here.
You need some javascript use JQuery.
<script type="text/javascript">
$(function(){
var array = [];
<?
if( $xml = simplexml_load_file('my.xml') ) {
$i=0;
foreach( $xml as $SAVED_EXPORT) {
$mfg = $SAVED_EXPORT->productmanufacturer;
}
}
foreach($mgf as $key=$value) {
// if $key in not numeric then add iterator for this foreach
echo "array[$key]=$value";
}
?>
iterator = 0;
$('#nextExport').click(function(){
var theInput = $('#setExport');
// theInput.attr('val',array[iterator]);
theInput.val(array[iterator]);
if(iterator==array.length) {
iterator = -1;
}
iterator++;
});
});
</script>
<form id="myform" method="post" action="coderdb.php">
<input type="text" id="setExport" value="<? echo $mfg[0] ?> name="MFG" />
<input type="button" id="nextExport" value="Next Export" />
<input type="submit" />
</form>
I hope this helps. if something goes wrong check the syntax , logic is right.
You need a way of keeping track of which array index you are at because as of right now you only have it set to a static number 0. So if you add a hidden form you can have it post the value that you are currently at and then using PHP you can increment it before displaying the new form. Also your form should point to the PHP document that it is on.
<?
if( $xml = simplexml_load_file('my.xml') ) {
foreach( $xml as $SAVED_EXPORT) {
$mfg = $SAVED_EXPORT->productmanufacturer;
}
}
if(isset($_POST["index"])) $index = $_POST["index"] + 1;
else $index = 0;
?>
<form id="myform" method="post" action="coderdb.php">
<input type="hidden" value="<? echo $index ?>" name="index" />
<input type="text" value="<? echo $mfg[$index] ?>" name="MFG" />
<input type="submit" />
</form>
Related
I’m new to PHP and making a website to add an arbitrary number of values in a given base. How would I generate several fields based on a user’s input in a previous field?
The simple code without any validation will be like this:
<?php
if (isset($_POST['count_of_fields'])) {
echo '<form method="POST" action="">';
for ($i = 0; $i < (int) $_POST['count_of_fields']; ++$i) {
echo '<input type="text" name="field[$i]" /><br>';
}
echo ' <input type="submit"></form>';
} else {
echo '
<form method="POST" action="">
<input type="number" name="count_of_fields">
<input type="submit">
</form>
';
}
Beside the answer from #lis-dev which is generating fields in server side you will have to load the page each time to render the new fields, let's use JavaScript to do that for you without refreshing the page. and yes using mix and max you can put limit also
function generate()
{
var value = parseInt(document.getElementById("no").value);
for(var i =1; i <= value ; i++)
{
var input = document.createElement("input");
var br = document.createElement("br");
input.type = "text";
input.placeholder = "I am dynamic field " + i;
document.getElementById('form').appendChild(input);
document.getElementById('form').appendChild(br);
}
}
<html>
<head>
<title>dynamic fields test</title>
</head>
<body>
<form id="form">
<input id="no" type="text" min="5" max="10" placeholder="Enter no of Fields">
<input type="button" value="Generate" onclick="generate()">
<br />
</form>
</body>
</html>
I'm having some difficulty updating a quantity value in a multi-dimensional array I've created and really hoping you can help me correct where I've gone wrong;
.
The background
I've got two "items" which both have a simple form tag followed by a hidden input field with a unique value (1 for the first item, 2 for the second).
The button will just point back to this same page using the POST method.
The div on the right of the page will then load a "basket" which will use these post values and add them to an array.
When the "add" button is used again the value should update to +1 rather than create another sub_array.
.
What is currently happening
Currently when I click "add" the first time it adds the array as expected;
However when clicking "add" for the second time it adds a second array rather than +1'in the quantity.
On the third time clicking "add" it does actually now find the original value and update it as I expected, if I click again and again it will continue to update the quantity
It just seems to be that second time I click "add".
.
The Script
<?php session_start();
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
if (ISSET($_POST["prod"]))
{
if(in_array($_POST["prod"],$_SESSION["cart"])==TRUE)
{
$_SESSION["cart"][0] =
array($_POST["prod"],$_POST["name"],$_SESSION["cart"][0][2]+1);
}
else{
echo 'running else';
$_SESSION["cart"]=array($_POST["prod"],$_POST["name"],1);}}
if ($_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
}
Sample form
<form action="test.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
Also, what you might well notice from my script is that when you "add" the second item it will actually overwrite the first one by creating the array from scratch so if you can help me with either or both of these I really would appreciate the expertise!
Many thanks to all in advance!
I tried to debug your code and a possible solution could be the following:
<?php
session_start();
if(!isset($_SESSION["cart"]))
{
$_SESSION["cart"]=[];
}
if (isset($_POST["prod"]))
{
$prod_id=$_POST["prod"];
//let suppose $_POST['prod'] is your item id
$found=false;
for($i=0;$i<count($_SESSION['cart']);$i++)
{
if(isset($_SESSION['cart'][$prod_id]))
{
echo "found! so add +1";
$_SESSION['cart'][$prod_id][2]+=1;
$found=true;
break;
}
}
if($found==false)
{
echo 'not found! so create a new item';
$_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
}
}
if (isset($_POST['e']) && $_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
?>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="2" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
Another way to do it is using associative arrays.
The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and
an array with properties as name=>value for each item.
session_start();
if(!isset($_SESSION["cart"]))
{
$_SESSION["cart"]=[];
}
//let's suppose you have unique names for items
if (isset($_POST["prod"]))
{
$name=$_POST["name"];
if(isset($_SESSION['cart'][$name]))
{
echo "found! so add +1";
$_SESSION['cart'][$name]['quantity']+=1;
}
else
{
echo 'not found! so create a new item';
$_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
}
}
if (isset($_POST['e']) && $_POST['e']=='1')
{
$_SESSION['cart'] =[];
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
?>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="2" name="prod" />
<input type="hidden" value="MAST-OMIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:
$_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);
For:
$_SESSION["cart"][0][2]+= 1;
By the way, try to properly indent your code when you are going to post it. It is hard to read.
I'm new here and a super noob in programming. I'm having trouble with my project. My problem is that I'd like hide the form after submit and retain the data input in it.
Here's my code:
<?php
$displayform = true;
if (isset($_POST['trck']))
{
$track = addslashes(strip_tags($_POST['tracknumber']));
$ord = $_POST['id'];
$displayform = false;
if (!$track)
echo "Please enter your tracking number!";
else
{
mysql_query("update `orderdetails` set `trackno`='$track' where `id`='$ord'");
}
if ($row2['id']==$ord)
echo $_POST['tracknumber'];
}
if ($displayform)
{
?>
<form method="post" action="">
<input type="text" name="tracknumber" id="tracknumber" size="30" maxlength="30" placeholder="Enter your track number here." />
<input type="hidden" name="id" value="<?php echo $row2['id']; ?>">
<input type="submit" name="trck" id="trck" value="Save" onclick="return confirm(\'Are you sure you want to save this tracking number?\');" />
</form>
</td>
</tr>
<?php
}
}
?>
This code was inside a while loop and my problem with this is that after I submit all the form is hidden. All I want is to hide the form with the specific ID on a query.
Simplest way is to use jQuery hide
Include the jquery as
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
$("#buttonid").click(function(){
$("#formid").hide();
});
You are looking for something like this in your <form> tag:
<form method="post" action="" id="awesome_form" onSubmit="document.getElementById('awesome_form').style.display = 'none';">
use the jQuery and use :
$("#submitButtonId").click(function(){
$('#formId').hide();
});
or else in pure javascript use
<input type="submit" value="submit" onClick="hideIt()"/>
<script type="text/javascript" >
function hideIt() {
document.getElementById('formId').style.display = 'none';
}
</script>
its better not to use inline javascript
Is it possible to create multiple html text inputs on my
<form method="POST" id="2">
using:
<input type="text" value="">
with an initial value of none and fill it with a value after clicking submit from a previous
<form method="POST" id="1">
Can anyone help me with this?
Thanks in advance! By the way, I'm using PHP.
This question is a bit vague and tagged incorrectly.
PHP is executed server side. The only way to modify your form is by using Javascript.
The answer to your "Is it possible" question is simply yes.
<form name="myform" action="handle-data.php">
Input: <input type='text' name='name' value='none' />
Submit
</form>
<script type="text/javascript">
function submitform()
{
// Do things here
document.myform.submit();
}
</script>
#zerey: I coded up this commented contrived example of what I think you might have been hoping to achieve using PHP only and I've combined it all into one form --
<?php
if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST")
{
$foo = intval($_POST['foo']);
$bar = $_POST['bar'];
if (count($bar) > 0)
{
// the additional inputs that were created now contains data
// and furter validation can take place here
}
}
if (!isset($foo))
{
$foo = 0; // default the # of inputs field to 0
}
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post">
<div>
<label for="foo"># inputs:</label>
<input type="text" name="foo" size="3" maxlength="1" value="<?php echo $foo; ?>">
<input type="submit" value="Submit">
</div>
<?php
// a check to limit the amount of additional inputs that can be
// created
if ($foo < 10 && $foo > 0)
{
?>
<div>
<?php
// loop to output the # of inputs the user previously entered
for ($i = 0; $i < $foo; $i++)
{
?>
<br>
<label for="bar[<?php echo $i; ?>]"><?php echo $i + 1; ?></label>
<input type="text" name="bar[<?php echo $i; ?>]" id="bar[<?php echo $i; ?>]" value="<?php echo $bar[$i]; ?>">
<?php
}
?>
</div>
<?php
}
?>
</form>
Do they have to be separate forms?
You could use something like the jQuery Form Wizard Plugin to split up the form in the UI and use the step_shown event to populate the fields you need.
How do I do unlimited fields in php? Here is the scenario:
At first, there are only 2 fields, lets called: first name1, last name1
What I want to do is, when I click the "add" button, it will add another 2 fields in new row, the fields label/name should be first name2, last name2. And when I click again, it will have first name3, last name3, and so on..
Can anyone give me some sample script in php? I am new to PHP.
The form should be in HTML. If somebody can give Ajax sample code, would be a big plus.
That depends on what you mean by "field." It sounds as though you're talking about a form, which wouldn't be PHP, but instead HTML. You could have a button [Add] post back to the server, which then refreshes the page with another set of form-inputs. You also do that via javascript without having to refresh the page.
Simple Javascript (jQuery) Example:
$(document).ready(function(){
$("input[value='Add']").click(function(event){
event.preventDefault();
$("p.field:last").clone().insertAfter("p.field:last");
});
});
<form method="post">
<p class="field">
<input type="text" name="firstname[]" value="" />
<input type="text" name="lastname[]" value="" />
</p>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
Simple PHP Example:
I don't encourage you use this as-is
<?php
$count = 1;
if ($_POST["submit"] == "Add") {
$count = ($_POST["firstname"]) ? (count($_POST["firstname"]) + 1) : 1;
} else
if ($_POST["submit"] == "Done") {
print "<pre>";
print_r($_POST["firstname"]);
print_r($_POST["lastname"]);
print "</pre>";
}
?>
<form method="post">
<?php for($i = 0; $i < $count; $i++) { ?>
<p class="field">
<input type="text" name="firstname[]" value="<?php print $_POST["firstname"][$i]; ?>" />
<input type="text" name="lastname[]" value="<?php print $_POST["lastname"][$i]; ?>" />
</p>
<?php } ?>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
There are two ways to do this, either using solely PHP or by some fancy JavaScript. I will tackle the PHP-only solution. A JavaScript solution would be much more responsive as there wouldn't be repeated round trips to the server but it would also only work for users who have JavaScript enabled, whereas a PHP solution works for everybody.
A general outline of the solution is this:
Initially $count is 1, and one row is generated.
If the user clicks Add, the form is posted back to the very same PHP file with a hidden count variable included. The script restarts from the beginning, increments $count, and displays one more row than the last time.
If the user clicks Submit, the names that have been entered are processed.
Here's some sample code. I apologize that I do not have PHP installed on the machine I'm writing this one so this is entirely untested. Hopefully there aren't too many horrendous syntax errors!
<?php
$count = isset($_POST['count']) ? $_POST['count'] : 1;
if (isset($_POST['add']))
++$count;
else if (isset($_POST['submit']))
{
header('Content-Type: text/plain');
print_r($_POST);
exit;
}
?>
<html>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post">
<input type="hidden" name="count" value="<?php echo $count ?>" />
<?php for ($i = 1; $i <= $count; ++$i) { ?>
[<?php echo $i ?>]
First: <input type="text" name="firstName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["firstName$i"]) ?>" />
Last: <input type="text" name="lastName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["lastName$i"]) ?>" />
<br />
<?php } ?>
<input type="submit" name="add" value="Add" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Oh and you want a JavaScript solution, eh? Well you've got the really nice jQuery answer already. How about a ridiculously long plain-JavaScript solution, then?
<html>
<head>
<script type="text/javascript">
// <![CDATA[
var count = 0;
function addRow() {
var table = document.getElementById("table");
var row = document.createElement("tr");
var countCell = document.createElement("td");
var countText = document.createTextNode(++count);
var firstCell = document.createElement("td");
var firstInput = document.createElement("input");
var lastCell = document.createElement("td");
var lastInput = document.createElement("input");
firstInput.type = "text";
firstInput.name = "firstName" + count;
lastInput.type = "text";
lastInput.name = "lastName" + count;
table .appendChild(row);
row .appendChild(countCell);
countCell.appendChild(countText);
row .appendChild(firstCell);
firstCell.appendChild(firstInput);
row .appendChild(lastCell);
lastCell .appendChild(lastInput);
}
// ]]>
</script>
</head>
<body>
<form action="somewhere.php" method="post">
<table id="table">
<tr>
<th>Row</th>
<th>First</th>
<th>Last</th>
</tr>
</table>
<script type="text/javascript">
addRow();
</script>
<input type="button" value="Add" onclick="addRow()" />
<input type="submit" value="Submit" />
</form>
</body>
</html>