Foreach selects the first check box only when checking

I am working on the following code to select checkboxes from a form. If I check the first checkbox, everything will be fine. If I check another box, I get an "Undefined index" error when submitting a bulkcopy form. Keep in mind that I get checkboxes with the post method, and the submit button is above the checkboxes due to the complexity of the layout of the form and fields. I need to basically select a few checkboxes and add specific values ​​to the database.

 <?php //bulkcopy.php session_start(); if($_SESSION['admin_logged_in'] != true){ header("Location:login.html"); exit(); } include 'db.php'; $from = mysql_real_escape_string($_GET['from']); $room = mysql_real_escape_string($_POST['room']); if(!empty($_POST['id'])) { foreach($_POST['id'] as $check) { $id = $check; $sel = mysql_query("select * from $from where id = '$id' limit 1 ") or die(mysql_error()); while($row = mysql_fetch_array($sel)){ $preview = $row['preview']; $text = $row['text']; $title = $row['title']; $images = $row['images']; } $ins = mysql_query("insert into $room (id, preview, text, title, images) values (' ', '$preview', '$text', '$title', '$images') ") or die(mysql_error()); } header("Location:admin.php"); } ?> 

The form code can be found below:

 <form class="form-inline" name="bulkcopy" method="post" action="bulkcopy.php?from=sights"> <b>Bulk Copy:</b> <select name='room' class="form-control"> <option>Select...</option> <option value="Orhan">Orhan</option> <option value="Deniz">Deniz</option> <option value="Irini">Irini</option> <option value="Katina">Katina</option> <option value="Gulbin">Gulbin</option> <option value="Mihalis">Mihalis</option> </select> <input class="btn btn-primary" type="submit" name="submit" value="Go"><br /><br /> </div> <table class="table table-bordered table-striped"> <th>Entry Name</th> <th>Display Order</th> <th>Copy to...</th> <th>Status</th> <th>Image</th> <th>Edit</th> <th>Delete</th> <th>Duplicate</th> <?php while($row = mysql_fetch_array($sel)) { ?> <tr> <td> <input type="checkbox" name="id[]" value="<?php echo $row['id']; ?>"> </form> <?php echo $row['title']; ?> </td> <td> <form name="order" method="post" action="sightorder.php?id=<?php echo htmlspecialchars($row['id']); ?>"> <div class="col-md-4"> <input class="form-control" type="number" name="order" value="<?php echo htmlspecialchars($row['ordernum']); ?>"> </div> <div class="col-sm-3"> <input type="submit" name="submit" value="Set Order" class="btn btn-primary"> </div> </form> </td> <td> <form name="copyto" method="post" action="copyto.php?from=sights&id=<?php echo htmlspecialchars($row['id']); ?>"> <input type="checkbox" name="room[]" value="Orhan"> O - <input type="checkbox" name="room[]" value="Deniz"> D - <input type="checkbox" name="room[]" value="Irini"> I - <input type="checkbox" name="room[]" value="Katina"> K - <input type="checkbox" name="room[]" value="Gulbin"> G - <input type="checkbox" name="room[]" value="Mihalis"> M <input type="submit" name="submit" value="Copy" class="btn btn-primary"> </form> </td> <td> <a href="sightstatus.php?id=<?php echo htmlspecialchars($row['id']); ?>&status=<?php echo $row['status']; ?>"><?php if($row['status'] == 1){ ?><i class="fa fa-check fa-lg"></i><?php }else{ ?><i class="fa fa-times fa-lg"></i><?php } ?></a> </td> <td> <a href="sightimages.php?id=<?php echo $row['id']; ?>"><i class="fa fa-image fa-lg"></i></a> </td> <td> <a href="editsight.php?id=<?php echo htmlspecialchars($row['id']); ?>"><i class="fa fa-edit fa-lg"></i></a> </td> <td> <a onclick="return confirmDelete()" href="delsight.php?id=<?php echo htmlspecialchars($row['id']); ?>"><i class="fa fa-trash fa-lg"></i></a> </td> <td> <a href="duplicatesight.php?id=<?php echo htmlspecialchars($row['id']); ?>"><i class="fa fa-copy fa-lg"></i></a> </td> </tr> <?php } ?> </table> 

Any help would be greatly appreciated. Thanks.

+8
html checkbox php foreach
source share
8 answers

You have a problem here.

 <?php while($row = mysql_fetch_array($sel)){ ?> <tr><td><input type="checkbox" name="id[]" value="<?php echo $row['id']; ?>"> <?php echo $row['title']; ?></td></form> 

There is no closing bracket for the while loop, and the form closes after adding the first flag. Therefore, if this check box is not selected, the input is not sent, so the index is undefined. Make sure you do not close the form until all lines have been added, for example

 <?php while($row = mysql_fetch_array($sel)){ ?> <tr><td><input type="checkbox" name="id[]" value="<?php echo $row['id']; ?>"> <?php echo $row['title']; ?></td></tr> <?php } ?> </table> </form> 
+2
source share

After viewing the raw HTML of the full page that you provided, it is clear that the problem is that you are trying to embed multiple forms which is invalid HTML. See this answer for more details. This answer does refer to a workaround , but it is an ugly hack and should probably be avoided.

I believe that a suitable, valid HTML solution in your case is to use one form. You currently have several nested forms that submit to the following locations:

  • bulkcopy.php? From = Attractions
  • sightorder.php? ID = 1
  • copyto.php from = sights & amp ;? ID = 1
  • copyto.php from = sights & amp ;? ID = 46
  • etc...

What you can do is have one form that determines what action to take based on the click of the submit button. For example:

 switch ($_POST['submit']) { case 'Go': // process bulkcopy break; case 'Set Order': // process siteorder break; // etc... } 
+1
source share

if the variable flag is $ _POST ['id'] table when you do it

 foreach($_POST['id'] as $check) { $id = $check; ... } 

if you do not check the first input of the first variable

 $check = $_POST['id']['0']; // is empty 

you can make another condition in foreach

 if(!empty($_POST['id'])) { foreach($_POST['id'] as $k=>$v) { if(!empty($v)){ $id = $v; $sel = mysql_query("select * from $from where id = '$id' limit 1 ") or die(mysql_error()); while($row = mysql_fetch_array($sel)){ $preview = $row['preview']; $text = $row['text']; $title = $row['title']; $images = $row['images']; } $ins = mysql_query("insert into $room (id, preview, text, title, images) values (' ', '$preview', '$text', '$title', '$images') ") or die(mysql_error()); } } header("Location:admin.php"); } 
0
source share

In your last generated html, the inputs you want to submit are not inside the bulkcopy form. As others pointed out, you have to change your html markup. One quick way to do this work without changing your markup is to use javascript. Just add this to the bottom of your html.It will take the input you want to submit and add it to the bulkcopy form.

  <script> $(document).ready(function(){ $('form[name="bulkcopy"]').submit(function( event ) { $('input[name="id[]"]').clone().hide().appendTo($(this) ); }); }); </script> 

You should also use mysql_num_rows() to check if you really have a result before trying to access them and use them to insert them into the database. The problem with your code is that the variables inside

  while($row = mysql_fetch_array($sel)){ .... } 

never defined if the result set is empty. But although they are never defined, you are trying to use them in the insert request later. Just check if you have the results first:

  <?php session_start(); if($_SESSION['admin_logged_in'] != true){ header("Location:login.html"); exit(); } include 'db.php'; $from = mysql_real_escape_string($_GET['from']); $room = mysql_real_escape_string($_POST['room']); if(isset($_POST['id'])&&!empty($_POST['id'])) { foreach($_POST['id'] as $check) { if(empty($check)) continue; $id = $check; $sel = mysql_query("select * from $from where id = '$id' limit 1 ") or die(mysql_error()); if(mysql_num_rows($sel)>0){ while($row = mysql_fetch_array($sel)){ $preview = $row['preview']; $text = $row['text']; $title = $row['title']; $images = $row['images']; } $ins = mysql_query("insert into $room (id, preview, text, title, images) values (' ', '$preview', '$text', '$title', '$images') ") or die(mysql_error()); } } header("Location:admin.php"); } ?> 
0
source share

Your form does not have a POST input named "room". Therefore, when you try to check it with this line $room = mysql_real_escape_string($_POST['room']); , in the array $_POST there is no element with the index " room ", therefore, the index error is undefined.

To debug such things, it is useful to parse the request / response headers in the submit form. If you use Chrome, press Ctrl + Shift + I to open the developer console, select the "Network" tab and when submitting the form, view the details of the entry that appears. You can see the names and values ​​of things sent here and give you an idea of ​​where everything is going wrong. Other browsers are available, and each has its own respectable version of it.

In addition, before accessing any variables that you yourself have not defined or cannot rely on (such as form submissions), you should use isset() to make sure the variable exists before using it - this will stop the error you are getting, as well let you catch where this is going wrong:

 if (!isset($_POST['room'])) { print('Please select something'); } else { $room = $_POST['room']; // technically not needed tho :p //... } 
0
source share
  <form bulkcopy> .... <table> <?php while: ?> // </form> it must be deleted ... <div sightorder> ... <input submit onclick="return send_sightorder(this);"> </div> ... <div copyto action="copyto.php?from=sights&id=<?php echo htmlspecialchars($row['id']); ?>"> ... <input submit onclick="return send_copy(this);"> </div> <?php end while ?> </table> </form> // bulkcopy close tag <script> /// Function send_sightorder is same. function send_copy(clicked_element) { var form = clicked_element.parent; var inputs = form.getElementsByTagName("input"); var data = inputs[0].name + "=" + inputs[0],checked + "&"; var URL = window.location.host + form.getAttribute("action"); for (i=1; i<inputs.length-1; ++i) { data = "&" + inputs[i].name + "=" + inputs[i].checked + "&"; } xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // redirect to new page or something else ... window.location = URL; } } xmlhttp.open("POST", URL,true); xmlhttp.send(data); return false; } </script> 
0
source share

which is the page you are calling, sightorder.php or copyto.php? which button to feed, set the order or copy?

in both cases you are sending a GET not POST identifier.

which is the line that causes the error?

Luke

0
source share

You created the problem yourself.

As I understand it, you are having trouble sending multiple checkboxes to the "Record Name" column with a "bulk copy" button.

So it should work. This is because you close your form in the "display order" column, which essentially makes it cointain only the first checkbox in it. If you want to publish all checked flags in a "bulkcopy" script, you will either have to declare it as a separate form for all flags, or use JS, for example. with jQuery enabled:

 // how to collect checked ids of checkboxes. var ids = []; var boxes = $('input[name="id[]"]'); for(var i in boxes) { if(boxes[i].checked) { ids.push(boxes[i]); } } 

to link something like the above, for example. on('click') your sumbit button. Here on SO there are pletny examples of how to prepare and submit a form using JS.

Edit:

there is an even easier way. You must add id to the form:

 <form class="form-inline" name="bulkcopy" id="bulkcopy" method="post" action="bulkcopy.php?from=sights"> 

and set your flags for it:

 <input type="checkbox" name="id[]" value="1" form="bulkcopy"> <input type="checkbox" name="id[]" value="46" form="bulkcopy"> 

which should easily fix your problem.

Remember to remove the extra closing form tags:

 // -----------------------------------------------------------v <input type="checkbox" name="id[]" value="1" form="bulkcopy"></form> 

they can easily damage your decision later. Just close right after your submit button:

  <input class="btn btn-primary" type="submit" name="submit" value="Go"><br /><br /> </form> 
0
source share

All Articles