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.
Related
In the form below, students are selected from student table in my DB. For each student selected a checkbox is checked if the student is absent and left unchecked if the student is present. The form is later on submitted for it to be inserted in the exam_status table in my DB.
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="matricule[]" value="<?php echo "$studentmatricule)"; ?>" readonly>
<label>Name</label>
<input type="text" name="name[]" value="<?php echo "{$studentname} {$studentsurname}"; ?>" readonly>
<label > Absent
<input type="checkbox" name="absent[]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
and my action page "action.php" is as follows
$matricule = $_POST['matricule'];
$absent=$_POST['absent'];
for ($i=0; $i<sizeof($matricule); $i++)
{
if($absent[$i]=='absent')
{
$status='absent';
}else{
$status='present';
}
$query = "INSERT INTO exam_status (student_matricule,status) VALUES ('". $matricule[$i] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
Now the issue is it doesn't just work as i want. the result always gives the first student absent and the rest present. I have tried all i can and have really researched too but with no success at all. Please anyone around to help me out?
Thanks in advance!
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
$index = 0;
while($row= $result->fetch_assoc())
{
$index++;
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][matriculate]" value="<?php echo $studentmatricule; ?>" readonly>
<label>Name</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][name]" value="<?php echo $studentname." ".$studentsurname; ?>" readonly>
<label > Absent
<input type="checkbox" name="studenInfo[<?php echo $index; ?>][status]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
Update your mail file like this. I have changed the form names into a single array. The reason is the checkbox values won't post to the page when the values are not checked. So its not possible to track which one was checked and which is not if you have same name.
And update your action.php like this,
<?php
$conn = mysqli_connect("localhost","username","password","db_name"); // update this values as per your configuration
$studenInfo = (!empty($_POST['studenInfo'])) ? $_POST['studenInfo'] : [];
foreach($studenInfo as $value ) {
$status = (isset($value['status'])) ? 'absent' : 'present';
$query = "INSERT INTO exam_status (student_name, student_matricule,status) VALUES ('". $value['name'] . "','". $value['matriculate'] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
?>
I have used my own table schema where i have added student_name in exam_status table for better tracking. Now you can see the values updating correctly. Also we can use bulk insert if we need to insert multiple data (Note : I haved used the bulk insert in this answer, i just followed the way you used)
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.
I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}
I am developing an ordering page in PHP for some products. The user needs to be able to select multiple types of products, so checkboxes will be necessary in the HTML form.
I've established an array for the checkboxes via the "name" attribute.
My problem is, I want to display what the user has selected on a confirmation page, so I'd like the "value" of those checkboxes to ultimately return a product name AND a product price. As far as I can tell I'm going to be stuck with one value only, so I've attempted to get around this:
<?php
//variables for the array and the count
$parray = $_POST['product'];
$pcount = count($parray);
//arrays for each product's information; i've only listed one for simplicity
$br = array("Big Red", 575);
/*The idea for this was for each product ordered to add a line giving the product information and display it. When the $key variable is assigned, it is stored simply as a string, and not an array (yielding [0] as the first letter of the string and [1] as the second), which I expected, but my general idea is to somehow use $key to reference the above product information array, so that it can be displayed here*/
if (!empty($parray))
{
for ($i=0; $i < $pcount; $i++)
{
$key = $parray[i];
echo "<tr><td height='40'></td><td>" . $key[0] . "</td><td>" . $key[1] . "</td></tr>";
}
}
?>
Is there anyway to make my $key variable actually act as if it is the array's name it is set to?
If not, is there any good way to do this?
So in your HTML table, you'll need to render each checkbox like this:
<input type="checkbox" name="selectedIDs[]" value="$key" />
where $key is the item number.
Then, in your PHP, you'll have a $_POST["selectedIDs"] variable, which is an array of all the item numbers that were checked.
Assuming you've got a product list array like this:
$products = array( 1 => array("Big Red", 575), 2 => array("Spearmint", 525));
You can then print a list of the selected products using a loop like this:
for($i = 0; $i < count($_POST["selectedIDs"]); $i++) {
$key = $_POST["selectedIDs"][$i];
$product = $products[$key];
echo "<tr><td height='40'></td><td>" . $product[0] . "</td><td>" . $product[1] . "</td></tr>";
}
The only real difference between this and what you wrote is that my $products array is two-dimensional, and my $key is used to grab the relevant product from the $products array.
You can give the value of the options the value of the ID of the corresponding item. Then you'll receive an array of ID's, which you can then again map to the $br array, where you look up the name and price of an item by its ID. You could use the array key as ID, so:
<!-- Form: -->
<input type="checkbox" name="product[]" value="1" />
<input type="checkbox" name="product[]" value="..." />
<input type="checkbox" name="product[]" value="15" />
[...]
<?php
$product = array();
$product[1] = array('name' => "Big Red", 'price' => 575);
$product[...] = array('name' => "...", 'price' => ...);
$product[15] = array('name' => "Small Green", 'price' => 475);
foreach ($_POST['product'] as $pId)
{
echo $products[$pId]['name'] . " costs " . $products[$pId]['price'];
}
?>
If of course your array originates from a database, you can use the table's ID's as values for the checkboxes. You could then implode the $_POST['product'] (of course after escaping it) with a comma, and use it in a SELECT ... WHERE ID IN ($productIds) query.
If i'm understanding you correctly, you'll have checkboxes something like this:
<input type="checkbox" name="product_id[]" value="1">Product #1<br/>
<input type="checkbox" name="product_id[]" value="2">Product #2<br/>
<input type="checkbox" name="product_id[]" value="3">Product #3<br/>
That should post whatever is checked as an array to your server.
gen_paper1.php
<div style="overflow: auto; height: 500px; border: 1px solid;">
<form action="" method="post">
<fieldset style="font-size: 15px; font-weight: bolder;">
<h4><u>Your Existing Header's are listed below</u> </h4>
<hr / >
<?php
$xhdr = mysql_query("SELECT * from s_user_header ORDER BY 'ASC'");
while($rheader = mysql_fetch_array($xhdr)){
$h = $rheader['h_content'];
$hid = $rheader['h_id'];?>
<script>
$(document).ready(function(){
//$('input[type=checkbox]').val('<?php echo $hid ; ?>').tzCheckbox({labels:['<?php echo $h; ?>','<?php echo $h; ?>']});
//$('#c').tzCheckbox({labels:['<?php echo $h; ?>','<?php echo $h; ?>']});
$('').tzCheckbox({labels:['<?php echo $h; ?>','<?php echo $h; ?>']});
});
</script>
<table>
<td><input type="checkbox" id="c" name="u_hdr[]" value="<?php echo $hid; ?>"></td>
<td style="font-weight: bolder"><?php echo $h."<br />"; ?></td>
</table>
<?php } ?>
</fieldset>
</div>
gen_paper2.....3.....
i need all this values in further page, so have taken hidden variables
<input type="hidden" name="hstdid" value="<?php echo $stdid; ?>">
<input type="hidden" name="hsubid" value="<?php echo $subid; ?>">
<input type="hidden" name="hdifid" value="<?php echo $difid; ?>">
<input type="hidden" name="hmarks" value="<?php echo $t_marks; ?>">
<input type="hidden" name="h_hid[]" value="<?php echo $hh; ?>">
gen_paper4.php
$getstdid = $_POST['hstdid3'] ;
$getsubid = $_POST['hsubid3'] ;
$getdifid = $_POST['hdifid3'] ;
$gethmarks = $_POST['htmarks'] ;
$hdr= $_POST['h_hdrid'] ;
$h = implode($hdr);
<table>
<?php
$h1 = explode(",",$h);
count($h1) . "<br />";
for($i=0;$i<count($h1);$i++){
$h1[$i];
$xheader = mysql_query("SELECT * from s_user_header WHERE h_id = ".$h1[$i]);
while($row = mysql_fetch_array($xheader)){ ?>
<tr>
<td><b>
<?php echo $i + 1 . ".   "; ?>
</b></td><td>
<?php echo $header = $row['h_content'] . "<br />";
?></td>
</tr>
<?php
}
}
//echo $header; ?>
</table>
I have a list
Each row has a common input field "sort_order" that's stored in MySQL db.
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I want to be able to change the sort order inline, without going into the edit form.
How do I get all the values into the database. I think I need to loop through each row adding the sort_order[row_id] and value to an array. But I am stuck on how to achieve this.
all the values are posting according to firePHP. sort_order[50] 1, sort_order[51] 2 etc.
New Attempt at explaining:
I have a list view with 2 input fields.
<input name="cat_id" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I have a function that's called on post in the controller:
public function sortOrderUpdate(){
//collect the values of cat_id and sort_order from each input into a array
//$this->request->post['sort_order']
//$this->request->post['cat_id']
//send to the model
$this->model_cat->updateCatSortOrder($sortorderarray);
}
And the database model file function:
public function updateCatSortOrder($sortorderarray){
foreach((int)$sortorderarray as $sort){
$this->db->query("UPDATE cat SET sort_order='" . (int)$sort['sort_order'] . "' WHERE cat_id = '" . (int)$sort['cat_id'] . "'");
}
}
Whats the best way to achieve this?
Just use empty square brackets:
<input type="text" name="sort_order[]" value"<?php echo $sort_order; ?>" />
You can then access the input as an array, saving you from building it yourself. It'll be stored as $_POST['sort_order'] (or $_GET, depending on the method attribute specified in your <form> tag).
On a related note, you should probably escape $sort_order when echoing it:
<input type="text" name="sort_order[]" value"<?php echo htmlspecialchars($sort_order); ?>" />
i would not recommend using [ ] in html names.
<input type="text" name="sort_order_<?php echo $row_id; ?>" value"<?php echo $sort_order; ?>" />
say, you have 50 input fields, when posted, you can build an array this way:
$sortorder = array();
for($i=0; $i<50; $i++){
$sortorder[] = $_REQUEST['sort_order_' . $i];
}
Ok this seems to work:
<input name="cat_id[]" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order[]" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
Controller:
public function updateCatSortOrder(){
$sortvals = $this->request->post['sort_order']; //$this->request->post same as $_POST
$row = $this->request->post['cat_id'];
$n = count($this->request->post['cat_id']);
$sortorder = array();
for($i=0; $i<$n; $i++){
$sortorder[] = array(
'cat_id' => $row[$i],
'sort_order' => $sortvals[$i]
);
}
$this->model_cat->updateCatSortOrder($sortorder);
}
Model:
//UPDATE CAT SORT ORDER
public function updateCatSortOrder($sortorder){
foreach($sortorder as $sort){
$this->db->query("UPDATE cat SET sort_order='" . $this->db->escape($sort['sort_order']) . "' WHERE cat_id = '" . $this->db->escape($sort['cat_id']). "'");
}
}