Post dynamic checkbox ids with values - php

Here is a form which contains dynamic checkbox retrieved from database table named "categories". All i am trying is to echo category id + name on a new page. I want all the selected categories with their ID's. the problem is the output shows the category names but it shows the last category id with each name.
Form
<form method="post" action="insert_try.php" enctype="multipart/form-data">
<label>Select categories</label>
<?php
$result = mysqli_query($con,"select * from categories");
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
?>
<br><input type="checkbox" name="categories_chk[]" value="<?= $row["cat_name"]; ?>"> <?= $row["cat_name"]; ?>
<input type="text" name="cat_chk_id" value="<?= $row["cat_id"]; ?>">
<?php
}
}
?>
<input type="submit" name="submit" value="Add">
</form>
insert_try.php
if(isset($_POST['submit'])) {
$cat_chk = $_POST['categories_chk'];
$cat_chk_id=$_POST['cat_chk_id'];
foreach ($cat_chk as $checkbox) {
echo $checkbox;
}
echo $cat_chk_id;

I don't know why you need this but in your case I would do this:
while($row = mysqli_fetch_array($result)) {?>
<br><input type="checkbox" name="categories_chk[<?= $row["cat_id"]; ?>]" value="<?= $row["cat_name"]; ?>"> <?= $row["cat_name"]; ?>
<?php
}
See, I set index of categories_chk as a category id.
If you print_r($_POST['categories_chk']) you will have a key=>value array where key is category id and value is it's name.
You can iterate over it kinda:
foreach ($_POST['categories_chk'] as $id => $name) {
echo 'Category id ' . $id . ' with name ' . $name;
}
Of course, I need to mention that $row["cat_id"] must be unique for such approach, otherwise you will have two same keys in array and the latter overwrites the previous one.

Related

How to store and get two values in PHP?

This is process_upcategory.php
I want to update the category name or the category id with another category name/id by its category id or by its category name.
I'm new to php
<?php
require('includes/config.php');
if(!empty($_POST))
{
$msg=array();
if(empty($_POST['cat']))
{
$msg[]="Please full fill all requirement";
}
if(!empty($msg))
{
echo '<b>Error:-</b><br>';
foreach($msg as $k)
{
echo '<li>'.$k;
}
}
else
{
$cat_nm=$_POST['cat[0]'];
$cat_id=$_POST['cat[1]'];
$query= "UPDATE `category` SET cat_nm='$cat_nm' WHERE cat_id='$cat_id'";
mysqli_query($conn,$query) or die("can't Execute...");
mysql_close($link);
header("location:category.php");
}
}
else
{
header("location:index.php");
}
?>
Now this is category.php, just a snippet of code. Not whole code
<form action='process_upcategory.php' method='POST'>
<b style="color:darkgreen">UPDATE CATEGORY </b> <br>
<b style="color:darkgreen">Old Category</b>
<br>
<select name="cat[]" multiple>
<?php
$query="select * from category ";
$res=mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($res))
{
echo "<option>".$row['cat_nm'];
echo "<option>".$row['cat_id'];
}
?>
</select>
<br>
<b style="color:darkgreen">New Category</b><br>
<input type='text' name='cat[0]'></input><br>
<input type='text' name='cat[1]'></input>
<input type='submit' value=' UPDATE '>
</form>
I want to update the category name with another category name by its category id or by its category name. I get undefined index cat[0] and cat[1]
When you end an input name with [] it wil be converted to an array by php. The correct way to get the values in this case would be something like this:
$cat=$_POST['cat'];
$cat_nm=$cat[0];
$cat_id=$cat[1];
I combined the two routines into one script.
I added 'sub' to the form to distinguish from when the form was submitted or not.
I used list() in the query result loop.Used mysqli_fetch_array($result, MYSQLI_NUM) rather than mysqli_fetch_assoc($res)
used foreach() to loop through the $_POST['cat']
Added 'value' to the <option value=""> to hold the id
Eliminated the switching from HTML mode to PHP mode by using HEREDOC.
<?php
if (intval($_POST['sub']) == 1){
$newcat = $_POST['new'];
foreach($_POST['cat'] as $key=>$value){
if(strlen($newcat[$key]) > 0){
mysqli_query($conn,"UPDATE `category` SET `cat_nm`='$newcat[$key]' WHERE `cat_id`='$value'");
}
}
}
echo <<<EOT
<html><head><style>h4,h3{color:darkgreen;margin:.2em;}</style></head><body>
<form action="#" method='POST'>
<h3>UPDATE CATEGORY</h3>
<h4>Old Category</h3>
<select name="cat[]" multiple>
EOT;
$sql="SELECT `cat_nm`, `cat_id` FROM `category` ";
$result=mysqli_query($conn,$sql);
while(list($cat_nm,$cat_id) = mysqli_fetch_array($result, MYSQLI_NUM)){
echo " <option value=\"$cat_id\">$cat_nm</option>\n";
}
echo <<<EOT
</select>
<h3>New Category</h3>
<input type="text" name="new[0]" /><br/>
<input type="text" name="new[1]" /><br/>
<input type="hidden" name="sub" value="1" /><br/>
<input type="submit" value=" UPDATE />
</form>
</body></html>
EOT;
?>

Unable to echo value from html <option> from while loop

i want to echo selected parent value. but i am getting error- Notice: Undefined index:
How can i echo selected parent value then? Whats wrong i am doing?
$q = mysql_query("SELECT * FROM menu");
echo '<form action="" method="post">
Menu name:<input type="text" name="mname"><br>
<select>';
while ($row = mysql_fetch_array($q)) {
$menu_name = $row['menu_name'];
echo '<option value="'.$menu_name.'">'.$menu_name.'</option>';
}
echo '</select><br>
<input type="submit" name="submit" value="Add Menu">
</form>';
if (isset($_POST['submit'])) {
echo $mname = $_POST['mname'];
echo $parent = $_POST[$menu_name];
}
add name to the select box and get the value of select box by name.
Updated code:-
$q = mysql_query("SELECT * FROM menu");
echo '<form action="" method="post">
Menu name:<input type="text" name="mname"><br>
<select name="menu_name">';
while ($row = mysql_fetch_array($q)) {
$menu_name = $row['menu_name'];
echo '<option value="'.$menu_name.'">'.$menu_name.'</option>';
}
echo '</select><br>
<input type="submit" name="submit" value="Add Menu">
</form>';
if (isset($_POST['submit'])) {
echo $mname = $_POST['mname'];
echo $parent = $_POST['menu_name'];
}
$_POST[$menu_name] probably doesn't exist, because only two elements in your form have name attributes. The text input and the submit input.
option elements aren't posted as part of the form, but rather the selected option's value for the select element. But your select element has no name, therefore no key to use in the key/value pair, so it isn't posted.
Give the element a name:
<select name="someName">
Then in the POST, you would be able to fetch the selected value just as you do for any other form element:
$_POST['someName']
You need to add name attribute to select tag.
echo '<form action="" method="post">
Menu name:<input type="text" name="mname"><br>
<select name="any_name">';
$q = mysql_query("SELECT * FROM menu");
while ($row = mysql_fetch_array($q)) {
$menu_name = $row['menu_name'];
echo '<option value="'.$menu_name.'">'.$menu_name.'</option>';
}
echo '</select><br>
<input type="submit" name="submit" value="Add Menu">
</form>';
if (isset($_POST['submit'])) {
echo $mname = $_POST['mname'];
echo $select_option_name = $_POST['any_name'];
}
Note: mysql_* functions are depricated, use mysqli_* functions

Working with checkbox from form array in php

Am looping products out from product table to add them to cart table. only the selected product by checking the checkbox should be added, but if you select, the selected ones do not correspond..
HERE IS THE HTML GETTING THE PRODUCTS OUT
<html>
<form action="#" id="" class="horizontal-form" method="post">
<?php
$LISTP = "SELECT * FROM products ORDER BY id";
$sn = 0;
$stmt = $pdo->prepare($LISTP);
$stmt->execute();
while($list = $stmt->fetch(PDO::FETCH_ASSOC)){
$sn = $sn + 1;
$ID = $list['id'];
$NAME = $list['name'];
?>
<input type="checkbox" name="slected[]" class="checkboxes" value="1" />
<input type="hidden" name="productid[]" class="" value="<?php echo $ID;?>" />
<input type="text" name="name[]" class="" value="<?php echo $NAME;?>" />
<?php }?> </form>
<?php
// now when we submot the form
$slected = $_POST['slected'];
$prod = $_POST['productid'];
$name = $_POST['name'];
foreach($prod as $key => $product){
if($slected[$key]>0){
echo $product.' '.$name[$key].' '.#$slected[#$key].'--<br>';
}
// the problem is here, if you check all product it will work well, but if you check the second one
// it would echo the second one giving it the name of the first one which was not checked at all
?>
I used to do this the same way in the past, and have discovered what I think is a better way. Rather than having a hidden input that stores the ID, just use the ID as the index for all of the form variable keys:
<input type="checkbox" name="slected[<?php echo $ID; ?>]" class="checkboxes" value="1" />
<input type="text" name="name[<?php echo $ID; ?>]" class="" value="<?php echo $NAME;?>" />
Then, your PHP can be simplified:
// now when we submot the form
$slected = $_POST['slected'];
$name = $_POST['name'];
foreach( (array)$slected as $ID => $on ) {
echo $product . ' ' . $name[$ID] . ' ' . $ID . '--<br>';
}
So - basically, your $slected variable will contain an array of only items that are selected, AND you have the product ID built in to the $slected array.

How to show checkboxes as checked when values are set in the database in codeigniter

I use foreach to show data came from database.
This is for Plan_data
<?php foreach ($veddingPlanData as $row) { ?>
<input box with value containing "echo row->value_name" >
<?php } ?>
This is for task data as check box [here I want to show the checkbox list in which the task is given to plan_id they appear as cheeked checkbox and remaining list with not checked status)
<?php foreach ($veddingPlanTaskMappingData as $row) { ?>
<input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" checked><?php echo $row->task_name?><br>
<?php } ?>
Here I show the whole task list in check box.
<?php foreach ($allVedingTasks as $row) { ?>
<input type="checkbox" name="task_id" value="<?php echo $row->task_id ;?>" ><?php echo $row->task_name?><br>
<?php } ?>
I want to foreach the task_name list with selected some task as there mapped plan_id.
Finally I found It
<?php
$arrSelVedTask = array();
foreach ($veddingPlanTaskMappingData as $row) {
$arrSelVedTask[$row->task_id] = '';
}
?>
<div class="form-group">
<lable for="task_id" class="control-label col-sm-12">Plan Task LIST:</lable>
<div class="col-sm-10">
<div class="checkbox" style="margin-left:40px;">
<?php foreach ($allVedingTasks as $row) {
if(isset($arrSelVedTask[$row->task_id])) {
?><input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" checked ><?php echo $row->task_name; ?><br><?php
}
else{
?><input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" ><?php echo $row->task_name; ?><br><?php
}
}
?>
Simply add a check:
<?php
foreach ($veddingPlanTaskMappingData as $row) {
$checked = ($row->task_id == YOUR_CONDITION) ? 'checked="checked"' : '';
?>
<input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" <?php echo $checked?>><?php echo $row->task_name?><br>
<?php } ?>
Use set_checkbox Of CI
<input type="checkbox" name="task_id" value="<?php echo $row->task_id ;?>" <?php echo set_checkbox('task_id', $row->task_id); ?> ><?php echo $row->task_name?>
at first in your model fetch the value of checkbox which is in your database then call that function in controller and pass the value to view page. then use if statement with every checkbox item to check whether the value is same or not. and write echo "checked";command if the condition match.
First of all we will take all the categories than we are taking an Id and using it for showing the checked list from the database. First we select the table values based on Id than we will fetch the record. We are having the data in the database column using , comma like 1,2,3,5,9. Than we save it in array and at last we just show that array to the page.
$table="select * from categorytable";
$this->result=mysqli_query($this->con,$table);
$this->count=mysqli_num_rows($this->result);
if($this->count < 1)
{
return "<div class='form-group'>".$messages->getResponseMessage("No category is added.", "Warning")."</div>";
}
else
{
$alert='';
$select="select Category from table where Id='$id'";
$result= mysqli_query($this->con, $select);
$amrow= mysqli_fetch_array($result);
$getAminity=$amrow["Category"];
$getArray= explode(",",$getAminity);
while($row= mysqli_fetch_array($this->result))
{
if(in_array($row[Id],$getArray)){
$alert.="<div class=col-md-2><label class='checkbox-inline'><input type=checkbox id='catval[]' checked name='catval[]' value='$row[Id]'/> $row[Name]</label></div>";
}
else
{
$alert.="<div class=col-md-2><label class='checkbox-inline'><input type=checkbox id='catval[]' name='catval[]' value='$row[Id]'/> $row[Name]</label></div>";
}
}

Submitting always gets the last value

<form action="" method="post">
<?php
include 'Includes/database_connection.php';
$sql = "select * FROM sims" ;
$result = mysql_query($sql,$con);
while($row = mysql_fetch_assoc($result)){
?>
<ul class="category_list">
<input type="hidden" value="$id1" name="hidden">
<li><?php echo $row['phonenr'];?><input type="hidden" value="<?php echo $row['id'];?>" name="id"></li>
</ul>
<?php
}
?>
<input type="submit" name="submit">
</form>
So i got the above form where you can select phonenumbers and when you submit them a database should be updated. And there are 23 id's in it. After submitting the form it always takes the last value. What am i doing wrong?
if(#$_POST ['submit'])
{
$id = $_POST["id"];
echo $id;
include 'Includes/database_connection.php';
mysql_query("UPDATE pairings SET sim_id='$id'
WHERE unit_id='$id1'")
}
Change your hidden field name to array like this
<input type="hidden" value="<?php echo $row['id'];?>" name="id[]">
then on PHP side use loop to retrieve
foreach ($_POST['id'] as $val) {
$id = $val;
include 'Includes/database_connection.php';
mysql_query("UPDATE pairings SET sim_id='$id'
WHERE unit_id='$id1'")
}
Slight modification specified by chandresh_cool, would get the result that you expect.
The input name is replaced with id, so the post key contains only the row[id], not the $_POST['id']
Instead change the name of the hidden field to accept as a array like this
<input type="hidden" value="<?php echo $row['id'];?>" name="id[]">
Then you can iterate id array as specified by chandresh_cool

Categories