I tried to passing the input value from user to another page by using the Session method after the user click on submit button.
My page has a form with one button which called as "Add Textbox". This button allow the user to add textbox by themselves.
Here is my current code
$(document).ready(function() {
var counter = 2;
$("#addButton").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' + '<input type="text" name="textbox' + counter + '" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function() {
if (counter == 2) {
alert("System required at least one.");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="<?php $_PHP_SELF ?>" method="post">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 :</label>
<input type='textbox' id='textbox1' name="textbox1">
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<br/>
<input type="submit" name="submit" id="submit">
</form>
And here is my code to assign the value to session in php
<?php
if(isset($_POST['submit'])) {
for($i=1; $i<=10; $i++)
{
if(isset($_POST['textbox'.$i]))
{
$obj = $_POST['textbox'.$i];
echo $obj,'<br>';
$_SESSION['textbox'.$i] = $obj;
}
}
header("Location:../brightan-system/result.php");
}
?>
and here is how I tried to get the value from the second page
<?php
for($i=1; $i<=10; $i++)
{
echo "<strong>".$i."</strong> ".$_SESSION['textbox'.$i]."<br>";//Use the session variables
}
session_destroy();
?>
Actually, I can get a result on the second page, but the problem is if the user only add 4 textboxes, then there will be an error that said Undefined index on the second page. This is because the for loop produce 10 session variable on the second page.
Is there another way to get the session variable instead using for loop in this case?
You should check first if ith textbox is set or not. Add condition to check before printing it.
<?php
for($i=1; $i<=10; $i++)
{
if(isset($_SESSION['textbox'.$i])){
echo "<strong>".$i."</strong> ".$_SESSION['textbox'.$i]."<br>";//Use the session variables
}
}
session_destroy();
?>
Related
I am trying to plus or minus 1, a simple quantity input box, which can be different like in the picture below :
PHP:
$query = ...
while ($row= mysqli_fetch_array($query))
{
<input type="hidden" value="<?php echo $row['id']; ?>" id="id_part">
<input type="text" value="<?php echo $row['quantity']; ?>" id="<?php echo $row['id']; ?>_count"><br>
<input type="button" value="-" id="minus" onclick="minus()">
<input type="button" value="+" id="plus" onclick="plus()">
}
Javascript:
<script>
var count = 1;
var id = document.getElementById("id_part").value;
var countEl = document.getElementById(id + "_count");
function plus(){
count++;
countEl.value = count;
}
function minus(){
if (count > 1) {
count--;
countEl.value = count;
}
}
</script>
It doesn't work. It takes me only the first id quantity box. Can't manage to edit the second quantity box, where the id should be different. As you can see, I assigned each id tag with different names, taken from database id.
Working fiddle.
That happen because you've a duplicate id's when the id attribute should be unique.
Please use common classes instead.
The ID id_part is being generated for every row in your script.
When you click on the button it finds the instance of id_part and its first value and edits its value.
Use unique ids say id='id_part' +<?php echo $row['id']; ?>
Actually your Hidden field ID should be unique but it is in loop and returning the same value for all rows.
<input type="hidden" value="<?php echo $q; ?>" id="**id_part**">
Try blow changes,
change your inner html as below
<input type="button" value="-" id="minus" onclick="minus(<?php echo $row['id']; ?>)">
<input type="button" value="+" id="plus" onclick="plus(<?php echo $row['id']; ?>)">
<script>
var count = 1;
function plus(position){
count++;
var countEl = document.getElementById(position + "_count");
countEl.value = count;
}
function minus(position){
if (count > 1) {
count--;
var countEl = document.getElementById(position + "_count");
countEl.value = count;
}
}
</script>
I'm stuck on this for a couple of days. I hope any of you can help me out.
Usually when you ask user input through an HTML form you can access the data by calling the $_POST function.
The problem in this approach is that I don't have a static set of input fields. When the user clicks on the addition button another input field shows up and they can make as many input fields as feel neccesary.
I do know that I should loop through it, but I don't have alot of experience in doing this. See the code below which adds dynamic rows in Jquery/Javascript:
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Source Name #'+ counter + ' : </label>' +
'<input type="text" placeholder ="Source Name" name="source_name' +
counter +
'" id="textbox' + counter + '" value="" > <label>IP address from #'+
counter + ' : </label>' +
'<input type="text" placeholder="IP Address From"
name="source_ip_from' + counter +
'" id="textbox' + counter + '" value="" > <label>IP address till #'+
counter + ' : </label>' +
'<input type="text" placeholder="IP Address Till"
name="source_ip_till' + counter +
'" id="textbox' + counter + '" value="" >'
);
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==2){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
The code below is where the form is created and posted in HTML/PHP
<form method="post" class="form-inline" action="addverkeersstroom.php">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Source Data : </label>
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0"
placeholder="Source" name="source_name">
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0"
placeholder="APP Nummer" name="source_app">
<?php
mysql_connect('localhost', '', '');
mysql_select_db('');
$sql = "SELECT * FROM zone";
$result = mysql_query($sql);
echo "<select name='zone_1' id='zone_1' class='form-control
ip_or_zone'>";
echo "<option value=''></option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='". $row['idzone'] . "'>" . $row['zone_naam'] . "
</option>";
}
echo "</select>";
?>
OR <input type="text" class="form-control ip_or_zone" placeholder="IP
Address from" name="source_ip_from">
<input type="text" class="form-control ip_or_zone" placeholder="IP
Address till" name="source_ip_till">
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0"
placeholder="NAT IP" name="source_nat">
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0"
placeholder="Netmask" name="source_netmask">
</div>
</div>
<input type='button' value='+' id='addButton'>
<input type='button' value='-' id='removeButton'>
And last but not least the code below that should insert it into the database.
<?php
session_start();
if(isset($_POST['submit'])) {
echo $source_name = $_POST['source_name'];
echo $source_app = $_POST['source_app'];
echo $source_zone = $_POST['zone_1'];
echo $source_ip_from = $_POST['source_ip_from'];
echo $source_ip_till = $_POST['source_ip_till'];
echo $source_nat = $_POST['source_nat'];
echo $source_netmask = $_POST['source_netmask'];
echo $destination = $_POST['destination'];
echo $dest_app = $_POST['destination_app'];
echo $dest_zone = $_POST['zone_2'];
echo $dest_ip_from = $_POST['dest_ip_from'];
echo $dest_ip_till = $_POST['dest_ip_till'];
echo $dest_nat = $_POST['destination_nat'];
echo $dest_netmask = $_POST['destination_netmask'];
mysql_connect('localhost', '', '');
mysql_select_db('');
//Maak een nieuwe verkeersstroom aan in de database
mysql_query("INSERT INTO verkeersstroom(changes_idchange, protocol, tcpudp,
port_nr)
VALUES('".$changeid."', '".$protocol."', '".$tcpudp."', '".$portnr."')");
$verkeerstroomid = mysql_insert_id();
//Maakt de eigenschappen van de verkeersstroom aan
mysql_query("INSERT INTO verkeersstroom_eigenschappen(changes_idchange,
verkeersstroom_idverkeersstroom, source_name, source_app, source_zone,
source_ip_from, source_ip_till, source_nat, source_netmask, destination,
destination_app, destination_zone, destination_ip_from, destination_ip_till,
destination_nat, destination_netmask)
VALUES('".$changeid."', '".$verkeerstroomid."', '".$source_name."',
'".$source_app."', '".$source_zone."', '".$source_ip_from."',
'".$source_ip_till."', '".$source_nat."', '".$source_netmask."',
'".$destination."', '".$dest_app."', '".$dest_zone."', '".$dest_ip_from."',
'".$dest_ip_till."', '".$dest_nat."', '".$dest_netmask."')");
header("Location:"."");
}
After submitting the dynamic values are like: source_name2, source_ip_from2, source_ip_till2, destination2, dest_ip_from2, dest_ip_till2
and counting up to the amount of rows generated by pressing the addition(+) button.
Like I said before I need to loop through the query somehow like this;
foreach source_name(or source_name2 or 3,4 etc), source_ip_from, source_ip_till, destination, dest_ip_from, dest_ip_till
Insert it seperately into the table like everything with a 2 in the same row and everything with a 3 in the same row and counting up like that.
I hope anyone can help me it is giving me an headache ;-p
html forms allow you to give input fields a name:
<input type='text' name='name' value='22'>
In the event you get multiple inputs but you do not know how many. You can make an array of the input fields by changing the <input name='name'> to <input name='name[]'>
Then you can write a simple for loop in php to work through the array:
<?php
$count = count($_POST['name']);
$name = $_POST['name'];
for($i = 0; $i < $count; $i++){
// do your sql stuff with:
$name[$i]; // this is the value of the inputfield number $i.
}
?>
Also I'd advice to look into using prepared statements. With your current php code you are vulnerable to SQL-injection.
<?php
$sql = "INSERT INTO verkeersstroom(`changes_idchange`, `protocol`, `tcpudp`, `port_nr`)
VALUES( ?, ?, ?, ?);";
$stmt = mysql_connect('localhost', '', '')->prepare($sql);
$stmt->bind_param("ssss", $changeid, $protocol, $tcpudp, $portnr);
$stmt->execute;
?>
This is an example, for more look at: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I am really stuck.
All i want to do is save a form not just the data into a session, the actual form. The idea is the administrator can add as many extra's to a product. My problem is i cannot work out how to save the form into a session (current code not working). I just cannot get my head around it. I am a newbie so i am getting rather confused.
At the moment i have the dynamic form but the form and data disappear on page refresh.
I have created the dynamic form:
var counter = 1;
var limit = 50; // the amount of addons that are allowed
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><label id='cat_label' name='cat_label' class='lab'>Name</label>\n\
<input type='text' id='cat_name' name='cat_name' value=''>\n\
<br>\n\
<label id='desc_label' name='desc_label' class='lab'>Description</label>\n\
<input type='text' id='cat_desc' name='cat_desc' value=''>\n\
<br>\n\
<hr id='dotted'>\n\
<br>\n\
<p id='menu_head'> Menu Item</p>\n\
<input type='button' value='Add New item to ...' onClick='addInput('new item');'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
<div id="dynamicInput">
<br><!--<input type="text" name="myInputs[]">-->
<label id="cat_label" class="lab">Name</label>
<input type="text" id="cat_name" name="cat_name[]" value="<?php print $_SESSION['form']['cat_name'][$counter]; ?>">
<br>
<label id="desc_label" class="lab">Description</label>
<input type="text" id="cat_desc" name="cat_desc[]" value="<?php print $_SESSION['form]['cat_desc'][$counter]; ?>">
</div>
<input type="button" value="Add" onClick="addInput('dynamicInput');">
<input type="submit" id="submit" name="submit" value="Save...">
</form>
I started this:
if (count($_POST) > 2 && $_POST['submit'] == "Save...") {
$countNumberOfInputs = count($_POST['cat_name']);
foreach($_POST as $key=>$value) {
if(!is_array($value)) {
$value = strip_tags($value);
$value = preg_replace("/[^0-9a-z -,.!]/i", "", $value);
}
$_SESSION['form'][$key] = $value;//save to session
}
if ($countNumberOfInputs < 1 ) {
$countNumberOfInputs = 1;
$counter = 0;
}
How can i resolve this, even better could someone highlight where i went wrong?
I need to create dynamic text fields which contains: name surname age gender. I should have a button called "add new user" which simply adds a new row where a I can type in name surname age gender. I need it dynamic because I don't know how many users will be added per event. I also need to store name surname age gender (x) amount of added rows in database.
I need something similar to below : however I need an additional 3 rows next to each other. So I will "INSERT INTO my_hobbies (name, surname, age, gender)
I know this sounds far fetched but i am struggling with this.
<?php
require("dbconn.php");
?>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Hobby No. ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />' );
});
});
</script>
<body>
<?php
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
foreach ( $_POST['dynfields'] as $key=>$value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')", $connection );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";
mysql_close();
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="add_field"><span>Click To Add Hobbies</span></p>
</div>
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
</body>
</html>
You already have a javascript counter so you can use it to identify which input fields belong together. According your example can use something like this:
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Hobby No. ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields['+counter+'][name]' + '" type="text" /><br />' +
+ '<input id="field_' + counter + '" name="dynfields['+counter+'][surname]' + '" type="text" /><br />' +
+ '<input id="field_' + counter + '" name="dynfields['+counter+'][age]' + '" type="text" /><br />' +
+ '<input id="field_' + counter + '" name="dynfields['+counter+'][gender]' + '" type="text" /><br />');
});
});
</script>
You can catch that in your PHP in the same way. Only notice that the value is now an array instead of a single value, but you can use array_keys and array_values to create the query on an easy way. Try this in PHP:
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
foreach ( $_POST['dynfields'] as $key=>$fieldArray ) {
$keys = array_keys($fieldArray);
$values = array_map("mysql_real_escape_string",$fieldArray);
$query = mysql_query("INSERT INTO my_hobbies (".implode(',',$keys).") VALUES ('".implode('\',\'',$values)."')", $connection );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";
mysql_close();
}
And yes, #alda1234 is right. You should't use mysql_* because it's deprecated.
I have the same answer with Mysqli prepared Statements enjoy it.
My html
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><label>Please enter your most recent education<br>
<input type="text" name="dynfields[]">
</p>
<p><label>Please enter any previous education<br>
<input type="text" name="dynfields[]">
</p>
<p><label>Please enter any previous education<br>
<input type="text" name="dynfields[]">
</p>
<input type="submit" name="submit">
</form>
and the php
foreach ( $_POST['dynfields'] as $key=>$value ) {
print_r($value."<br>");
$stmt = $conn->prepare("INSERT INTO dynamic_test2 (hobbies) VALUES (?)");
$stmt->bind_param("s", $values);
$values = $conn->real_escape_string($value);
$stmt->execute();
echo "New records created successfully";
}
My code is trying to allow user to add new text field by clicking the add button. I want to post all the text fields the user had added (be it 2, 3, 4 or more) to the next page so I can retrieve the data that the user had entered.
P/S: Added new requirement: Retrieve data and print the data that the user had entered.
Here is my code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var counter = 2;
$("#addMenuTab").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Menu Tab #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeMenuTab").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
</script>
<form name="basicInfo" action="contents.php" method="post">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Menu Tab #1 : </label>
<input type='text' id='textbox1' >
</div>
</div>
<br/>
<input type='button' value=' Add Menu Tab ' id='addMenuTab' />
<input type='button' value=' Remove Menu Tab ' id='removeMenuTab' />
</form>
</body>
</html>
You can get all these fields and their values on contents.php under $_POST global array.
For example:
<?php
echo "<pre>";
print_R($_POST);
echo "</pre>";
?>
I have a simple solution for your problem.
Use one counter to count the number of textfields.
We can later pass this variable to html.
Modify your javascript:-
<script>
$(document).ready(function(){
var counter = 2;
$("#count").val(counter-1);
$("#addMenuTab").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Menu Tab #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
$("#count").val(counter);
counter++;
});
$("#removeMenuTab").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
$("#count").val(counter-1);
});
});
</script>
Now add one hidden field in your html form. The value of this hidden field will be the total number of texfields.
<input type='hidden' id='count' name='counter' value=''/>
In your contents.php add the below given code.
$count=$_POST['counter'];
for($i=1;$i<=$count;$i++)
{
echo "value from textbox$i is".$_POST["textbox$i"]."<br/>";
}
Here you will get the total number of textfields in the variable $count
Since the name of your texfields are like textbox1,textbox2..etc You can use a loop for getting all the data from your previous page using the POST method.
Also add name attribute to your initial textbox to get this work.
<input type='text' id='textbox1' name="textbox1" >
I don' understand what is your question. If you add some inputs like textbox10, you will be able to read textbox10 without problems on your server.