guys. I was going ok with my app until I got to this type of form, written below. I have 2 items in this table and the ID's are "1" and "2". Even though, if I press "Submit" on the "1" ID item, it prints me "2" every time. Does anyone have a clue what might be the problem? Thank you.
<form method="POST">
<?php
$query = "SELECT * FROM table";
while($row = $query->fetch_array())
{
$id = $row['id'];
?>
<input type="hidden" name="id" value="<?php echo $id; ?>" >
<input type="submit" name="submit">
<?php } ?>
</form>
<?php
if(isset($_POST['submit']))
{
echo $_POST['id'];
}
?>
You're outputting two items into the same form with the same name. When you click the Submit button, it gathers all of the fields in the form based on the name attribute and sends them on to wherever the form is being posted.
If you want to have a button that submits each ID with a separate button, you'd want to try having a new form for each ID. There are other ways of doing this too, but based on your current code, try something like this:
<?php
$query = "SELECT * FROM table";
while($row = $query->fetch_array())
{
$id = $row['id'];
?>
<form method="POST">
<input type="hidden" name="id" value="<?php echo $id; ?>" >
<input type="submit" name="submit">
</form>
<?php } ?>
<?php
if(isset($_POST['submit']))
{
echo $_POST['id'];
}
?>
Related
I have created a database in phpMyAdmin with table for topics such as Math, Physics etc. Each topic has a topic_id as primary key in table tb_topic. Each topic can have multiple videos. Admin can add videos to each topic which requires topic_id as foreign key in table tb_video_management to store videos against a topic.
Backend:
There is a button to add videos in form.php
form.php:
<?php
$query = "SELECT topic_id, topic_name,aid FROM tb_topic";
$result = $con->query($query);
while($query_row = mysqli_fetch_assoc($result)) {?>
<tr>
<td><form action='edit.php' method='get'>
<button type='submit' name='edit' id = 'edit' value='<?php echo $query_row['topic_id'];?>' class='btn btn-success'>EDIT</button><br />
</form></td>
</tr>
<?php
} ?>
When this button is clicked, page is navigated to another page "edit.php" which has 2 buttons, one for add new video and second for viewing video gallery.
edit.php:
$id = $_GET['edit'];
echo 'topic id----> ' . $id;
<form action='add_video.php' method='get'>
<button type='submit' name='add' id = 'add' value='<?php echo $id;?>' class='btn btn-success'>ADD NEW VIDEO</button>
</form>
<form action="video.php" method="get">
<button type="submit" name="goback" id="goback" value="submit" class="btn btn-primary">VIEW GALLERY</button>
</form>
The class where videos are added has a form for topic name, details etc.
add_video.php
$id = $_GET['add'];
echo 'topic id----> ' . $id;
<form action="add_video.php" method="post">
Video Title: <input type="text" name="video_name"><br />
Video Detail: <input type="text" name="video_detail"><br />
Video Question: <input type="text" name="video_question"><br />
Video Link: <input type="text" name="video_link"><br />
<input type="submit" name="submit" value = "Submit"><br />
</form>
When "submit" button is clicked, following code executes:
if(isset($_POST['submit'])) {
if(!(empty($_POST['video_name']) || empty($_POST['video_detail']) || empty($_POST['video_question']) || empty($_POST['video_link']))) {
$name = $_POST['video_name'];
$detail = $_POST['video_detail'];
$question = $_POST['video_question'];
$link = $_POST['video_link'];
$insert = "INSERT INTO tb_video_management(topic_id, video_name, video_detail, video_question,video_link) VALUES ('$id','$name','$detail', '$question','$link')";
if(!mysqli_query($con,$insert))
echo "error";
header('location:edit.php');
}
}
The problem I am facing is, when I click submit button, the value in $id is lost (may be because another button (submit) is pressed) and it fails to insert the record as there is no value for "topic_id" anymore. I cannot resolve this issue of keeping foreign key value even after pressing submit button.
So far I have been creating extra table to hold value for topic_id which is definitely not the right approach.
To use the $id into another page, you must have to store that in such a way that it will be remain exist after submit.That can be done by using the hidden field.
You may set the value of $id like:
<input type="hidden" name="topic_id" value="<?php echo $id?>">
Once you submit and redirect to add_video.php, you may get the value of $id same as another field video_detail.
On submit look like:
if(isset($_POST['submit'])) {
$topic_id = $_POST['topic_id'];
}
I am using a form having select dropdown. I want to pass the value obtained from the selected option as a $_GET request in form action field but any ways to access it outside the foreach loop. Here is the code sample that I have written
<form id="dynamicForm" action="client-detail-dynamic.php?id=<?php echo $_GET['id']; ?>&r_id=<?php **PASS THE DROPDOWN VALUE ID HERE** ?>" method="post">
<select class="form-control" id="dynamicfy" name="dynamicfy">
<?php
$j = 0;
foreach($payment_data as $pd):
?>
<option value="<?php echo $payment_data[$j]->r_id; ?>"><?php echo $payment_data[$j]->fy; ?></option>
<?php $j++; endforeach; ?>
</select>
</td>
<td class="col-md-4">
<input type="submit" name="submit" id="submit" class="btn btn-sm btn-success">
</td>
</form>
NOTE: $payment_data is an array containing the table data with field names r_id, fy etc
I have two methods for this.
First method
Create a hidden field inside form element to store the value of id.Put form action null
<form id="dynamicForm" action="" method="post">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
On submit you will get two values
if(isset($_POST['submit'])){
$id=$_POST['id'];
$r_id=$_POST['dynamicfy'];
header("location: client-detail-dynamic.php?id=" . $id . "&r_id=" . $r_id . "");
exit();
}
Second method use javascript
<select class="form-control" id="dynamicfy" name="dynamicfy" onchange="rdrt(this.value)">
<script>
function rdrt(str){
id=<?php echo $_GET['id']; ?>;
if(str!=""){
location.href="client-detail-dynamic.php?id=" + id + "&r_id=" + str;
}
}
</script>
Rather than changing the page from FORM ACTION what you can do is pick the values and set them in url passed to header:location.
try this.
``<?php
if(isset($_POST['submit'])
{
$option = $_POST['dynamicfy'];
$id = $_POST['id']
header('location: http://client-detail-dynamic.php?id=$id,r_id=$option');
}
?>
<form id="dynamicForm" action="" method="post">
<select class="form-control" id="dynamicfy" name="dynamicfy">
<?php
$j = 0;
foreach($payment_data as $pd):
?>
<option value="<?php echo $payment_data[$j]->r_id; ?>"><?php echo $payment_data[$j]->fy; ?></option>
<?php $j++; endforeach; ?>
</select>
</td>
<td class="col-md-4">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>
<input type="submit" name="submit" id="submit" class="btn btn-sm btn-success">
" />
</td>
</form>
What you are trying to do is go somewhere based in the $_GET['id]. That's not possible server side as you have to FIRST make the request, then execute code. If your aren't trying to bring form data with you to this URL, then try this suggestion. However forget what I about not possible. you could do something like:
<?php
if(isset($_POST['submit-button'])) {
header("location: file.php?something=" . $_GET['id']);
}
// set the form action to nothing and add this to the same page the form is on
// and you can redirect based on the $_GET['id']
?>
To change value on selection of dropdown, You will need to use a jQuery on change of select box.
Please refer following code for same.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(Document).ready(function() {
jQuery('#dynamicfy').change();
});
jQuery('#dynamicfy').change(function() {
jQuery('#dynamicForm').attr('action', 'client-detail-dynamic.php?id=' +<?php echo $_GET['id']; ?> + '&r_id=' + jQuery(this).val());
});
</script>
if you just want selected dropdown on the action page then You may also get selected dropdown on the action page with using $_POST['dynamicfy'] on action page "client-detail-dynamic.php"
I need to delete a record, in this case a categories from my forum, from the database based on its id.
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
{
?>
<td>
<form method="post">
<input type="hidden" value="<?= ['cat_id']; ?>">
<input type="submit" name="submit" value="Remover" />
</form>
<?php
if(isset($_POST['submit']))
{
mysql_query("DELETE FROM categories where cat_id = 'cat_id'");
}
?>
</td>
<?php
}
?>
i cant get a "good" way to do it... :(
EDIT: This is for a programming lesson not a real forum!!
Your HTML Input Field needs a name so it can be identified by your PHP.
Then, in your Code Block where you attempt to delete the category, you need to acces the category id using the $_POST array.
Another thig you want to do is read up onj the dangers of SQL injections.
If you're just playing around with PHP and MySQL at the moment: Go Ahead. But if you actually want to develop, maybe you should read up on a few other things as well, even if it seems like overkill at first: PHP The Right Way.
Nontheless, try this:
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
{
?>
<td>
<form method="post">
<input type="hidden" name="hid_catid" id="hid_catid" value="<?php echo $cat_id; ?>">
<input type="submit" name="submit" value="Remover" />
</form>
<?php
if(isset($_POST['submit']))
{
$query = "DELETE FROM categories where cat_id = '".(int)$_POST['hid_catid']."'";
mysql_query($query);
}
?>
</td>
<?php
}
?>
--> hidden field should have name and id to use
--
Thanks
Your hidden input field needs a name to be accessable after the post. Also I am not sure if ['cat_id'] is the correcty way to reference this variable. Where does it come from?
<form method="post">
<input type="hidden" name="cat_id" value="<?= $cat_id ?>">
<input type="submit" name="submit" value="Remover" />
</form>
Then your query has to look like this to correctly grab the id from the post.
mysql_query("DELETE FROM categories where cat_id = " . mysql_real_escape_string($_POST['cat_id']));
I have a page that is created dynamically from the information that a user has submitted on a previous page. For example on page 1, the user inputs some department names. They can enter as many as they want. On page 2, multiple sections are created for each department that was entered on page one. Inside each of these sections are going to be forms, I currently have it set up so that the names of the forms are created using a variable $a. I need to know how to post these items once the submit button in each section is clicked. I have tried several different ways and nothing is working. I want it so that ONLY the items with the same $a value as the submit button's $a get posted.
$departmentSql = "SELECT * FROM b_departments WHERE loc_id='$locid' AND b_id = '$bid'";
$departmentResults = mysql_query($departmentSql,$con);
$a = 0;
while ($departmentRow = mysql_fetch_array($departmentResults)) {
$department = $departmentRow['b_dep_name'];
$departmentID = $departmentRow['dep_id'];
$b_departmentID = $departmentRow['b_dep_id'];
$a++;
echo "
<div id=depDiv>
<div id=depDivHeader>
".$department."
</div>
";
$areaSql = "SELECT * from areas WHERE dep_id = $departmentID ORDER BY area_name ASC";
$areaSqlResult = mysql_query($areaSql);
?>
<br />
<input type="hidden" name="bdep<?php echo $a;?>" value="<?php echo $b_departmentID; ?>" />
Add Area:
<select name="dep_area<?php echo $a;?>" type="menu">
<option value=""></option>
<?php while($areaRows=mysql_fetch_assoc($areaSqlResult)){?>
<option value="<?php echo "".$areaRows['area_id'].",".$areaRows['area_name']."" ?>"><? php echo $areaRows[ 'area_name'] ?></option>
<?php }
?>
</select>
<input type="submit" name="areaSub<?php echo $a;?>" value="Add" />
<?php
echo "</div>";
}
?>
*EDIT I need everything to be in one form because the point of the page is to add up all of the values that will be inserted into each of the individual sections later. *
**EDIT 2 :
I figured it out using #dirt 's jquery suggestion.
HTML:
$departmentSql = "SELECT * FROM b_departments WHERE loc_id='$locid' AND b_id = '$bid'";
$departmentResults = mysql_query($departmentSql,$con);
$a = 0;
while ($departmentRow = mysql_fetch_array($departmentResults)) {
$department = $departmentRow['b_dep_name'];
$departmentID = $departmentRow['dep_id'];
$b_departmentID = $departmentRow['b_dep_id'];
$a++;
echo "
<div id=depDiv>
<div id=depDivHeader>
".$department."
</div>
<div id=$a>
";
$areaSql = "SELECT * from areas WHERE dep_id = $departmentID ORDER BY area_name ASC";
$areaSqlResult = mysql_query($areaSql);
?>
<br />
<input type="hidden" name="bdep<?php echo $a ?>" value="<?php echo $b_departmentID; ?>" />
Add Area:
<select name="dep_area<?php echo $a ?>" type="menu">
<option value=""></option>
<?php while($areaRows=mysql_fetch_assoc($areaSqlResult)){?>
<option value="<?php echo "".$areaRows['area_id'].",".$areaRows['area_name']."" ?>"><? php echo $areaRows[ 'area_name'] ?></option>
<?php }
?>
</select>
<button type="submit" name="areaSub" value="<?php echo $a ?>" />Add</button>
<?php
echo "</div></div>";
} ?>
jQuery:
<script>
$(document).ready(function() {
$('#<?php echo $a ?>').submit(function() {
.post("include/action.php")
});
});
</script>
PHP:
if(isset($_POST['areaSub'])) {
$areaval = intval($_POST['areaSub']);
$area = mysql_real_escape_string($_POST["dep_area".$areaval.""]);
list($area_id, $area_name) = explode(',', $area, 2);
$bdep = mysql_real_escape_string($_POST["bdep".$areaval.""]);
echo $areaval;
echo $area_name;
echo $bdep;
}
EDIT: If its a single form with multiple sections and you don't want to trim out unwanted form data after the POST then I think you must use jQuery to trim the form values prior to the post to the server, so see my jQuery portion below for a crued example of how you would go about only posting the data for the selected button.
Short answer would be to use the Name/Value attributes of the submit button and evaluate that once posted. Multiple buttons with the same name can have different values and the values don't have to be the labels.
Example:
<form id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<button type='submit' name='submit' value='<?php echo $a; ?>'>Add</button>
</form>
...
<form id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<button type='submit' name='submit' value='<?php echo $a; ?>'>Add</button>
</form>
...
<?php
# _POST:
if (isset($_POST['submit']) && $_POST['submit'] == '1') {
echo 'Department 1';
}
if (isset($_POST['submit']) && $_POST['submit'] == '2') {
echo 'Department 2';
}
?>
You could also use jQuery to get all elements contained in a certain Div ID. Something like (this is rough idea):
<div id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<input type="submit" name="areaSub<?php echo $a;?>" value="Add" />
</div>
jQuery:
$('#<?php echo $a; ?>').submit(function() {
do_something_with_form_$a
});
I'm not sure if I understand completely... but the issue you're having is that, when a user hits the 'submit' button for a given set of values (a given department), it submits ALL of the data on the page? And you only want the input fields for that specific area submitted?
Section off forms with the tag:
<form> </form>
So, you'll have multiple areas:
while(...) {
<form method="..." name="form $a">
<input name="... $a">
<input name="... $a">
...
<submit>
</form>
}
(Obviously this is pseudocode, adjust accordingly)
The way I've structured my form data is by creating them in a while loop, but each time they are created the form will take a unique id.
So my question is, how do I access them individually and update specified data to a MYSQL server.
I've attempted to do it in the code at the end of the script, but I'm not sure how to access the forms individually
<?php
include 'user_data.php';
include 'core.inc.php';
$query = mysql_query("SELECT `post_text` FROM `posts`,`sub_posts` WHERE sub_posts.post_id = posts.id AND sub_posts.user_id='$user_id'");
while($row = mysql_fetch_array($query)){
?><?php echo $row[post_text].'<br>'?>
<form action="<?php $curent_file ?>" method="POST">
<textarea name="answer_field" > </textarea><br />
<input type="submit" value="Submit Answer">
<input type="hidden" name="post_id" value="<?php echo $row['post_id']; ?>" />
</form>
<?php
}//While Loop
if (isset($_POST['answer_field']) && !empty($_POST['answer_field'])){
$answer = mysql_real_escape_string($_POST['answer_field']);
$id = intval($_POST ['post_id']);
$query = "UPDATE `sub_posts` SET `sub_answer`='$answer' WHERE `post_id`='$id'";
}
?>
Only a single form gets posted when clicking the "submit" field. The form name does not get submitted by itself. Instead, you would place the post ID to which the form corresponds as a hidden field:
<input type="hidden" name="post_id" value="<?php echo $row['post_id']; ?>" />
And then later:
$answer = mysql_real_escape_string ($_POST ['answer']);
$id = intval ($_POST ['post_id']);
$query = "UPDATE `sub_posts` SET `sub_answer`='{$answer}' WHERE `post_id`={$id}";
Note that you definitely need to escape the answer before putting it in the query and make sure that the ID is a number. Otherwise, you're opening up your code to SQL injection attacks.