I am building a page in which I have 2 select boxes. I add items to Select #2 from Select #1.
When the submit button is clicked, I want to get all options only from Select #2 whether they are selected or not.
<?php
require('handlers/handler.php');
$active = $_POST['activeProperties'];
$slider = $_POST['sliderProperties'];
$array = array();
if(isset($_POST['submit'])){
if(isset($_POST['sliderProperties'])){
foreach($_POST['sliderProperties'] as $item){
$array[] = $item;
}
}
echo "<pre>";
print_r($array);
echo "</pre>";
}
?>
<form method="post" style="height: 600px;">
<select id="source" name="activeProperties[]" data-text="Source list" data-search="Search for options" style="height: 600px;">
<?php
$query = $handler11->query("SELECT ID, name FROM properties WHERE active = 'yes' ");
while($row = $query->fetch()){
echo '<option value="'.$row['ID'].'">'.$row['name'].'</option>';
}
?>
</select>
<select id="destination" name="sliderProperties[]" data-text="Destination list" data-search="Search for options">
</select>
<input type="submit" name="submit" class="btn btn-primary" value="Save"/>
</form>
I am only getting the first item in the select box with this code. How can I get all items?
You can use the multiple select of HTML (documentation here), try this:
<form method="post" style="height: 600px;">
<select multiple id="source" name="activeProperties[]" data-text="Source list" data-search="Search for options" style="height: 600px;">
<?php
$query = $handler11->query("SELECT ID, name FROM properties WHERE active = 'yes' ");
while($row = $query->fetch()){
echo '<option value="'.$row['ID'].'">'.$row['name'].'</option>';
}
?>
</select>
</form>
the other option is doing through Javascript.
If you want all the data if selected or not, cant you get the same result in your php by this query :
$query = $handler11->query("SELECT ID, name FROM properties WHERE active = 'yes' ");
Related
I'm using ajax to take user input in a dropdown menu (so the input would be the chosen alternative) and show some information after a button is clicked. It works, but I want to use a switch case statement in the controller, which is not working.
I have this piece of code to populate the dropdown menu:
<form method="post" action="controleur.php">
<select name="liste_formations" id="liste_formations" class="form-control">
<option value="">Choisissez une formation</option>
<?php
while($row = mysqli_fetch_array($result))
{
echo '<option value="'.$row["idActivite"].'">'.$row["nom"].'</option>';
}
?>
</select>
</div>
<div class="col-md-4">
<input type="submit" name="action" class="btn" id="search" value="Voir informations" />
</form>
And when the user clicks the send button it goes to controller.php where I have:
case "Voir informations":
$idActivite = $_POST['liste_formations'];
$query = "SELECT * FROM formation WHERE idActivite = '$idActivite'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$data["nombreMaxPart"] = $row["nombreMaxPart"];
$data["idFormateur"] = $row["idFormateur"];
$data["prix"] = $row["prix"];
$data["description"] = $row["description"];
}
echo json_encode($data);
break;
When I try to do that I get the information I want, but in a blank page with the information vector. I actually want to show it in a table.
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 have a table item (id, name, content, categories id (foreign key table category)) and a category table (id, title)
name: type text
content: textarea
categories_id: select dynamics related to the category table
Inserting the item table that works very well but in the modification. I have a problem with the dynamic select to the list of categories, not pick me a choice that I chose to add a article.
How I can get the value of the select tag? <select> <option></option> </select>
<?php
include 'dbconnect.php';
$id = $_GET['id'];
$sql = mysql_query("SELECT * FROM articles WHERE id ='".$id."'");
$res = mysql_fetch_assoc($sql);
if (#$_REQUEST['do'] == "update") {
$m_id = $_POST['id'];
$nom = $_POST["nom"];
$contenu = $_POST["contenu"];
$categories_id = $_POST["categories_id"];
$sql = mysql_query("UPDATE articles SET nom='$nom', contenu='$contenu', categories_id='$categories_id' WHERE id =' $m_id' ");
if($sql)
header("Location:listArticles.php");
else
header("Location:updateArticle.php");
}
?>
<html lang="en">
<body class="nav-md">
<?php if (isset($_GET['id']) && $_GET['id'] == $id) { ?>
<form action="" method="post" accept-charset="utf-8">
<table>
<td>Nom: <input type ="text" name ="nom" value="<?php echo $res['nom'] ?>"></td>
</br>
<td>Contenu: <textarea name ="contenu"><?php echo $res['contenu'] ?></textarea></td>
</br>
<td>
Categories:
<select class="form-control" name="categories_id" value="<?php echo $res['categories_id'] ?>" >
<option></option>
</select>
</td>
<td>
<button type="submit" class="btn btn-success" name ="do" value="update">Modifier</button>
</td>
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
</table>
</form>
<?php } ?>
</body>
</html>
That is what the page currently looks like:
If I understand you correctly (and judging by the picture), you want to show the categories and select the category associated with the article.
Here's a rough, untested sketch of how you can approach. Read my comments also.
<?php
include 'dbconnect.php';
// assuming ID is integer, we'll use intval()
$id = isset($_GET['id']) ? intval($_GET['id']) : null;
// query article matching given ID
$articleRes = mysql_query("SELECT * FROM articles WHERE id ='" . $id . "'");
$article = mysql_fetch_assoc($articleRes);
// query categories
$categoriesRes = mysql_query("SELECT * FROM categories");
// check if form has been submitted
// if you are expecting POST, use $_POST not $_REQUEST
// don't use #, it's sloppy
if (!empty($_POST['do'])) {
$m_id = $_POST['id'];
$nom = $_POST["nom"];
$contenu = $_POST["contenu"];
$categories_id = $_POST["categories_id"];
// update article with given ID
// is it nom or name?
$updateRes = mysql_query("UPDATE articles SET nom='$nom', contenu='$contenu', categories_id='$categories_id' WHERE id='$m_id'");
if ($updateRes) {
header("Location: listArticles.php");
} else {
header("Location: updateArticle.php");
}
// good practice to die after you redirect
die();
}
?>
<html lang="en">
<body class="nav-md">
<?php if ($article) : ?>
<form action="" method="post" accept-charset="utf-8">
<table>
<td>Nom: <input type="text" name="nom" value="<?php echo $article['nom'] ?>"></td>
<!-- you cannot have a BR tag in between TD tags -->
<!--/br-->
<td>Contenu: <textarea name="contenu"><?php echo $article['contenu'] ?></textarea></td>
<!-- you cannot have a BR tag in between TD tags -->
<!--/br-->
<td>
Categories:
<!-- SELECT tag does not have a VALUE attribute -->
<select class="form-control" name="categories_id">
<!-- loop through the categories and build the OPTION tag -->
<!-- for each iteration, check if the category ID matches the article's category ID -->
<!-- if so, mark the option as selected -->
<?php while ($category = mysql_fetch_assoc($categoriesRes)) : ?>
<option <?php echo $category['id'] == $article['categories_id'] ? 'selected' : '' ?>><?php echo $category['title'] ?></option>
<?php endwhile ?>
</select>
</td>
<td>
<!-- unnecessary to have VALUE attribute as this element will always be submitted -->
<button type="submit" class="btn btn-success" name="do">Modifier</button>
</td>
<input type="hidden" name="id" value="<?php echo $article['id'] ?>">
</table>
</form>
<?php endif ?>
</body>
</html>
Additional points:
Stop using mysql_* functions! They are deprecated for good reasons. Use mysqli_* or better PDO functions.
Your queries are prone to SQL injection.
When mixing PHP control structures (e.g. if, while, etc) with HTML, I like to use their alternative syntax (e.g. if (condition): and endif; while (condition): and endwhile; etc). It looks more readable, imo.
I am using the ternary operator which is a shorter syntax for simple if/else statements.
Add comments!
Update your update query:
$sql = mysql_query("UPDATE articles SET nom='$nom', contenu='$contenu', categories_id='$categories_id' WHERE id ='$m_id' ");
For suggestion:
use mysqli_() as mysql_ are depreciated please follow the link: Why shouldn't I use mysql_* functions in PHP?
take care of sql injection
don't suppress the warning using (#)
i have this html for that displays 2 dropdown. one is for category and second is for subcategory
<form action="a_insert_product.php" method="post">
<div class="module_content">
<fieldset>
<label>Category</label>
<select name="catname">
<?php
$sql = "SELECT * FROM category";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result))
{
$catname=$row["catname"];
$catid=$row["id"];
?>
<option value="<? echo $catname.'-'.$catid;?>"><? echo $catname;?></option>
<?}
}?>
</select>
</fieldset>
<fieldset>
<label>Subcategory</label>
<select name="subcatname">
<?php
$sql = "SELECT * FROM subcategory";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result))
{
$subcatname=$row["subcatname"];
$subcatid=$row["id"];
?>
<option value="<? echo $subcatname.'-'.$subcatid;?>"><? echo $subcatname;?></option>
<?}
}?>
</select>
</fieldset>
<fieldset>
<label>Product Name</label>
<textarea rows="2" name="prodname"></textarea>
</fieldset>
</div>
<footer>
<div class="submit_link">
<input type="submit" name="submit" value="Submit" class="alt_btn">
</div>
</footer>
</form>
Although it is working fine but i wish to display the subcategory according to the category that is selected in the category dropdown, i don't have much knowledge regarding javascript. can anyone plz tel how it can be done
You can do it using AJAX, for example, assign an "id" attribute to both your catname and subcatname dropdowns:
<select name="catname" id="category-dropdown">
<select name="subcatname" id="subcategory-dropdown">
And then use some AJAX magic, for example:
<script type="text/javascript">
$("#category-dropdown").change(function() {
var selection_value = $(this).val();
$.post("subcategories.php", { category: selection_value },
function(result){
$.each(result, function(index, subcat) {
var option_html = "<option>" + subcat.name + "</option>";
$("#subcategory-dropdown").append(option_html);
}
},
"json");
});
</script>
Please note that this example uses jQuery, so you will have to add it to your page before using. Also, you will need to create a PHP page that will provide you with the response for subcategories, in this case I have used JSON, which is fairly easy to use.
I would do the following:
On the first dropdown, you'd have an on change handler which checks for what is selected in the dropdown. I would link that to an ajax call which then brings in the correct data to allow you to populate the second dropdown.
Google or search on here "JQuery on change" and "JQuery ajax" - there's tons of resources out there.
This is a different approach to same ends
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)