So I am new to PHP and I'm trying to create a spreadsheet-like program. I have a form with columns and cells, and the user can add and delete rows (using Javascript). Once the data in the cells has been entered, the user can save the sheet and the data is displayed in the same cells. I have been able to get this to work, but I have to manually check each input and put the data into a variable, and then display that variable in the cells. I'm trying to find a way to automatically get all the data from the cells, and store each one into a variable with incrementing id's. The problem is, I want the user to be able to add infinite rows with infinite cells; so how would I get all the data if I don't know how many cells there will be?
I don't know if I am even going about this the right way, so I'm hoping someone can at least point me in the right direction. Like I said, I'm new to PHP so I may be completely ignorant and thinking about this completely wrong.
Note: I'm not looking for a copy/paste answer, but more of guidance on the theory of accomplishing this. Of course the plan is to eventually store all the inputted data into a MySQL table, and then display it on the screen from there; but, I'm first trying to solve this problem.
This is what I have so far:
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$a1_post = $_POST['a1'];
$a2_post = $_POST['a2'];
$a3_post = $_POST['a3'];
$b1_post = $_POST['b1'];
$b2_post = $_POST['b2'];
$b3_post = $_POST['b3'];
}
HTML
<form class="table-form" method="post" action="">
<div class="column" id="column-a">
<p>Antigen</p>
<input class="cell" id="a1" type="text" name="a1" value="<?php echo $a1_post; ?>">
<input class="cell" id="a2" type="text" name="a2" value="<?php echo $a2_post; ?>">
<input class="cell" id="a3" type="text" name="a3" value="<?php echo $a3_post; ?>">
</div>
<div class="column" id="column-b">
<p>Start Size</p>
<input class="cell" id="b1" type="text" name="b1" value="<?php echo $b1_post; ?>">
<input class="cell" id="b2" type="text" name="b2" value="<?php echo $b2_post; ?>">
<input class="cell" id="b3" type="text" name="b3" value="<?php echo $b3_post; ?>">
</div>
<input class="submit" type="submit" value="Save">
</form>
As long as you use a naming convention you can just iterate over $_POST and update your table as necessary...
To simplify this process name your inputs with square brackets:
<input class="cell" id="c1" type="text" name="c[0]" value="<?php echo $c[0]; ?>" />
<input class="cell" id="c2" type="text" name="c[1]" value="<?php echo $c[1]" />
When you submit your data will already be in an array per row:
$_POST would equal
[
'c' => ['c1 value', 'c2 value']
];
So you can interact with your dataset by iterating over $_POST:
foreach ($_POST as $rowName => $row) {
//$row equals ['c1 value', 'c2 value']
}
Related
I have a problem in automating a form with hidden inputs in PHP. Basically I'm doing an input for a barcode scanner where the user will input the barcode and it will auto-submit, just like in a cash registry.
The conflict which I think is the cause of the problem is because of a conditional form. Here is a snippet:
<form method="post" id="form1">
<div class="products">
<input type="text" name="code" class="form-control" autofocus required onchange="submit()" />
</div>
</form>
<?php
$query = 'SELECT * FROM product WHERE PRODUCT_CODE='.$code.' GROUP BY PRODUCT_CODE ORDER by PRODUCT_CODE ASC';
$result = mysqli_query($db, $query);
if ($result):
if(mysqli_num_rows($result)>0):
while($product = mysqli_fetch_assoc($result)):
?>
<form id="form2" method="post" action="pos.php?action=add&id=<?php echo $product['PRODUCT_CODE']; ?>" >
<input type="hidden" name="quantity" class="form-control" value="1" />
<input type="hidden" name="name" value="<?php echo $product['NAME']; ?>" />
<input type="hidden" name="price" value="<?php echo $product['PRICE']; ?>" />
<input type="submit" name="addpos" style="margin-top:5px;width: 462px" class="btn btn-info" value="Add"/>
</form>
<?php
endwhile;
endif;
endif;
?>
<script>
function submit() {
document.getElementById("form1").submit();
}
document.getElementById("form2").submit();
</script>
The data from form1 has no trouble auto-submitting, then the form2 will auto-submit but nothing happens. I need help on how can I make form2 auto-submit correctly too. I have tried different event handling for form2 but nothing happens. I only know a little bit of javascript so that's just how my script turned out.
Thank you, Programming kings!
Because the second form is inside the while loop, if there are multiple results there will be multiple forms with the same id = "form2".
You need an increment variable $incrm = 2 inside the loop,
form id='form<?php echo $incrm;?>',
with $incrm++ before ending it. I also recommend to add ann onchange event to the last input 'price' ; onchange = submit(this).
function submit(inp) {
inp.parentElement.submit();
}
I've got a php page that gets data from mysql database as $certs[] and populates that as a table:
($db is read from file, it is constant)
<?php echo $cert["id"] ?>
<button type="button" class="awe" title="Edit" id="editbtn" onclick="openNewModalWithValue('Modal2')" value =<?php echo $cert["id"] ?> ></button>
<form action="sample.php" method="POST">
<input type="hidden" name="id" value=<?php echo $cert["id"] ?>>
<input type="hidden" name="db" value=<?php echo $db ?>>
<button type="submit" name="mission" title="Delete"></button>
</form>
And I try to get id value in Modal window. (Like press 'EDIT' button and you get modal window with values set.) So my Modal window is:
<form id="modal-form" method="POST" action="sample2.php">
<input type="number" id="idb" name="idbase" />
<input type="text" id="nme" name="name"/>
<input type="hidden" name="db" value=<?php echo $db; ?>>
<input type="hidden" id= "idbs" name="idbs" />
<button id="form-submit" type="submit" >Edit</button>
</form>
and the Javascript for opening modal window is:
function openNewModalWithValue(modal){
document.getElementById(modal).style.display = "block";
document.getElementById("idb").value = document.getElementById("editbtn").value;
}
The problem is that even though PHP sends $certs[] values correctly, and table populates correctly, when I hit 'edit' button, I get preserved values of item#1 in PHP array, no matter which row/data I click.
Is there an easier way rather than applying counter to every row and operating with it?
Problem may be idb is multiple id in DOM. document.getElementById find Dom in whole page. so you must provide unique id
How can I make a form like posting my ingredient but in the way that I will only edit the posted ingredients
this is the Javascript of the button
<script>
$(document).ready(function() {
var max_fields = 25; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="col-md-6 div-' + x + '"><input type="text" class="form-control" name="mytext[]" required/></div>'); //add input box
$(wrapper).append('<div class="col-md-6 div-' + x + '"><input type="text" class="form-control" name="mytext2[]" required/>Remove</div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(".div-" + $(this).attr("div-id")).remove();
x--;
})
});
</script>
This is the form of inserting the ingredients
<div class="input_fields_wrap">
<div class="col-md-6">
<h5>Notes/Scaling (quantity, additional info)</h5>
<input type="text" class="form-control" name="mytext2[]" required>
<br>
</div>
<div class="col-md-6">
<h5>Name of Ingredient:</h5>
<input type="text" class="form-control" name="mytext[]" required>
<br>
</div>
<br>
</div>
<div class="col-md-12">
<button class="add_field_button button loading-pulse">Add More Fields</button>
</div>
this is how i implode it
$ingredient_name =implode("^",$_POST["mytext"]);
$ingredient_value = implode("^", $_POST["mytext2"]);
this is how i explode it
$ingredient_name = explode("^",$ingredient_name);
$ingredient_value = explode("^", $ingredient_scale);
$ingredients = array_combine($ingredient_value,$ingredient_name);
this is how i loop it
<table class="table-bordered" style="width:90%;">
<th style="text-align:center;">Ingredient Scale</th>
<th style="text-align:center;">Ingredient Name</th>
<?php
foreach($ingredients as $amount => $name)
{
?>
<tr>
<td style="margin:left:10px;"><?php echo "{$amount}"?></td>
<td style="margin:left:10px;"><?php echo "{$name}"?></td>
</tr>
<?php
}
?>
</table>
for example in the database
there are 2 columns,
recipe_ingredient_value recipe_ingredient_name
1/4,1/2,1 cup sugar,meat,water
i want it to extract into an input fields that i can edit (rename, add ,delete)
for example
1/4 sugar remove
1/2 meat remove
1 cup water remove
add more fields
You should print all values in a form inside the loop and then you need some sort of "Save" button and a route ready to receive new values. This route should be a php script, for example, that would loop through your new data and perform an update.
I'm suggesting you're writing PHP framework-free, standalone app. That way you have to think about a lot of things, which is good for you if you are a beginner.
Now back to the point:
It would be great if you could print a hidden id of a database row, somewhere inside the loop:
<tr>
<td><input type="text" name="recipe_id" value="<?php echo $amount; ?> /></td>
<td><input type="text" name="recipe_id" value="<?php echo $name; ?> /></td>
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?> />
</tr>
Remember that route that collects and updates the data? Let's call it "update-script.php".
The update-script.php should perform a check for every field in a $_GET or $_POST variable, to see if that value has been changed. If yes, the row should be updated, if not, then it should be skipped. It's up to you to create the logic for this.
Furthermore, I noticed that your javascript code needs some adjustments. I will only hint one thing that kinda sticks out:
$(add_button).click(function(e){
For the sake of your future work, please use "on" method that is described here:
http://api.jquery.com/on/
Trust me, when you start working with DOM elements, changing the DOM and adding new events, this will be your savior.
Good luck!
I think the easiest way would be to structure your inputs like this.
<tr>
<td>
<input type="hidden" name="recipe[<?= $recipe_id; ?>][id]" value="<?php echo $recipe_id; ?>" placeholder="value"/>
<input type="text" name="recipe[<?= $recipe_id; ?>][value]" value="<?php echo $value; ?>" placeholder="name"/>
</td>
<td><input type="text" name="recipe[<?= $recipe_id; ?>][name]" value="<?php echo $name; ?>" /></td>
<td><input id="recipe_<?= $recipe_id; ?>" type="checkbox" name="recipe[<?= $recipe_id; ?>][delete]" value="1" /><label for="recipe_?= $recipe_id; ?>">Delete</label></td>
</tr>
Where $recipe id is the row id. Then your javascript would add more rows like
<tr>
<td><input type="text" name="recipe[2][value]" value="" placeholder="value" /></td>
<td><input type="text" name="recipe[2][name]" value="" placeholder="name" /></td>
<td></td>
</tr>
Then in your php you can see the array will be formatted nicely into arrays of recipes like:
array(
array(
'name' => 'Pie'
'value' => 2
'recipe_id' => 1
),
array(
'name' => 'Deleted Pie'
'value' => 2
'recipe_id' => 2
'deleted' => 1
),
array(
'name' => 'New pie'
'value' => 2
),
)
Then using the deleted key you can check if you need to delete the Database row and if it has the recipe_id key then it might need to be updated. If it doesn't have the recipe key then its a new recipe.
I got a post form and the issue is that It errors when I try to post a link like https://www.google.com/ into an imput type text, It akts as some command I do not understand, anyway heres my code and let me know what exactly is wrong.
<?php
if(isset($_POST['add'])){
$animeid = $_POST['animeid'];
$number = $_POST['number'];
$code = $_POST['code'];
echo $animeid;
echo $number;
echo $code;
}
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="600" border="1" cellspacing="1" cellpadding="2">
<tr>
<br>
<input class="inputs" placeholder="Link" name="code" type="text" id="code">
</br>
<br>
<input class="inputs" placeholder="ID" name="id" type="number" id="id">
</br>
<br>
<input class="inputs" placeholder="Number" name="number" type="number" id="number">
</br>
<br>
<center><input class="btnExample" name="add" type="submit" id="add" value="Add Episode!"></center>
</td>
</tr>
</table>
</form>
And its a simple thing really If Id to type anything other than a link it would work but I need it to be a link and thats that , I still can't see why from dosen't post links and Id like to know how can I make it post links.!
OK I think I know how to solve It But Only Know How To I will really need help on it as I did not learn javascript but There should be a way to remove the http:// or https:// before Posting The FORM And then Ill reADD it in the PhP but Now What I got To Figure It Is How Can I make a javascript that will autoremove http:// or https:// Before posting The FORM , Thanks for the Answers You Gave Me Till Now , I will apriciate If SOmeone Will Know How to autoremove words with javascript Thanks !
Well Its Simple , I Figured that Links act as A Code that wants to be posted to so what acutally happens when You Post it Its Simple Instead of Posting It To http://anime4life.net/ it Posted It To http:// linkthatIinitiallyTypedIntheInput+anime4life.net which caused to have a very long and unsucessful end
Well The Solution Is Simple , First AutoRemove The http:// straight as Im TYping Using JsQuery Like This
$('input').change( function() {
var input = $('input');
input.val(
$('input').val().replace(/https?:\/\//gi,'')
);
});
And Then That Posts The Form
Next in the echo Use This
<?PHP
echo "https://".$_POST['code']."";
And That Puts It Back For The Display , Well Thankyou All For Trying To Help!
Action is where you're sending the data to get posted (i.e. #) for same page
You need to run a set check on each variable. i.e.:
if (isset($_POST['fromPerson']){
$fromPerson=$_POST['fromPerson'];
}
change
<form method="post" action="<?php $_PHP_SELF ?>">
in
<form method="post" action="?">
and change
<?php
if(isset($_POST['add'])){
$animeid = $_POST['animeid'];
$number = $_POST['number'];
$code = $_POST['code'];
echo $animeid;
echo $number;
echo $code;
}
?>
in
<?php
echo (isset($_POST['animeid'])) ? $_POST['animeid'] : '';
echo (isset($_POST['number'])) ? $_POST['number'] : '';
echo (isset($_POST['code'])) ? $_POST['code'] : '';
?>
your code
<?php
echo (isset($_POST['animeid'])) ? $_POST['animeid'] : '';
echo (isset($_POST['number'])) ? $_POST['number'] : '';
echo (isset($_POST['code'])) ? $_POST['code'] : '';
?>
<form method="post" action="?">
<table width="600" border="1" cellspacing="1" cellpadding="2">
<tr>
<br>
<input class="inputs" placeholder="Link" name="code" type="text" id="code">
</br>
<br>
<input class="inputs" placeholder="ID" name="id" type="number" id="id">
</br>
<br>
<input class="inputs" placeholder="Number" name="number" type="number" id="number">
</br>
<br>
<center><input class="btnExample" name="add" type="submit" id="add" value="Add Episode!"></center>
</td>
</tr>
</table>
</form>
I'm sure this has been asked befor but I can't seem to find it in a search
I have multiple forms on a page generated by php all with onCick event
The problem is it only picks up the first event after that any other clicks produce same result from first click
Here is javascript
function CompareScores(form)
{
var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;
if(scoreA > scoreB){
alert('Score A is Larger ' + scoreA)
}else{
alert('Score B is Larger ' + scoreB)
}
}
And the php generating forms
<?php
while($i<=$numPrelimTeams) {
if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
<input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
<input type="hidden" name="game" value="<?php echo $game_num; ?>">
<p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
}else{
?>
<p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
<input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">
</form><br><br><br>
<?php
$game_num++;
$e=$e+2;
}
$i++;
}
?>
Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.
Since you're already sending the form object, use that instead:
var scoreA = form.score_A.value;
...
There is essentially a single problem with your code. You have multiple instances of the same ID.
To fix it, try something like this.
<input type="text" class="small score_A" name="score_A" size="1" />
Similarly
<input type="text" class="small score_B" name="score_B" size="1" />
Now, you can write a querySelector in your JS
function CompareScores(form) {
var a = form.querySelector('.score_A').value;
var b = form.querySelector('.score_B').value;
//do something
}