Getting Array Value from Checkbox in PHP - php

I am trying to build a list where user can select any checkbox and it can send all select values for the row to the next page.
Here is what I have:
first page:
<table border="0">
<tr>
<td>Check All | Uncheck All</td>
<td>Item Name</td>
<td>Item Description</td>
</tr>
<?php
if ($num_rows == 0) {
return "No Data Found";
}else{
while ($row = dbFetchAssoc($result)) {
$item_id = $row['item_id'];
$item_name = $row['item_name'];
$item_desc = $row['item_desc'];
$item_qty = $row['item_qty'];
$item_upc = $row['item_upc'];
$item_price = $row['item_price'];
$vendor_id = $row['vendor_id'];
?>
<tr>
<td> <input type="checkbox" name="area[]" value="<?=$item_id?>" /></td>
<td><input type="text" name="item_name[]" value="<?=$item_name?>"></td>
<td><input type="text" name="item_desc[]" value="<?=$item_desc?>"></td>
</tr>
<?php
}
}
?>
<tr><td colspan="3"><input type="submit"></td></tr>
</table>
</form>
Next Page:
<table>
<tr><td colspan="3"><?php "Total Item(s) selected: "; echo count($_POST['area']); ?></td></tr>
<?php
if(!empty($_POST['area'])) {
foreach($_POST['area'] as $check) {
echo "<tr><td>".$check."</td><td>".$_POST['item_name']."</td><td>".$_POST['item_name']."</td></tr>";
}
}
?>
</table>
I need to read the item_name and item_desc value as well. How do I get it?

You need the key:
if(!empty($_POST['area'])) {
foreach($_POST['area'] as $key => $check) {
echo "<tr><td>".$check."</td><td>".$_POST['item_name'][$key]."</td><td>".$_POST['item_desc'][$key]."</td></tr>";
}
}
As Marc said in his answer it would probably be better to set key's in your loop creating the input.
<?php
if ($num_rows == 0) {
return "No Data Found";
}else{
$counter = 0;
while ($row = dbFetchAssoc($result)) {
$counter++;
$item_id = $row['item_id'];
$item_name = $row['item_name'];
$item_desc = $row['item_desc'];
$item_qty = $row['item_qty'];
$item_upc = $row['item_upc'];
$item_price = $row['item_price'];
$vendor_id = $row['vendor_id'];
?>
<tr>
<td> <input type="checkbox" name="area[<?=$counter?>]" value="<?=$item_id?>" /></td>
<td><input type="text" name="item_name[<?=$counter?>]" value="<?=$item_name?>"></td>
<td><input type="text" name="item_desc[<?=$counter?>]" value="<?=$item_desc?>"></td>
</tr>
<?php
}
}
?>

foreach($_POST['area'] as $key => $check) {
echo $check . $_POST['item_name'][$key];
}
assuming that there's an exact 1:1 correspondence between your three submitted arrays. Remember that checkboxes which are NOT checked do NOT get submitted with the form, so this is most likely NOT true and this code will not work as written.

Related

Any way to break up data into array?

Problem
So a have some php code that gets student info from the db and outputs that info. The info is outputted in a input so the user can edit that info. Then when the user is done editing the info, I need to get the data, which I have. My problem is that I don't know how to break up that info so it's easy for me to alter the info in the db.
Student Table
studentID | firstname | lastname | teacherID
PHP Code that has the inputs
<form action="server/edit/students.php" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Teacher's Firstname</th>
<th>Teacher's Lastname</th>
</tr>
<?php
// get student info
$getStudent = $link->prepare("SELECT * FROM students");
$getStudent->execute();
$getStudent = $getStudent->fetchAll(PDO::FETCH_ASSOC);
$value = 0; // counts rows
// loop through each student
foreach ($getStudent as $student) {
$studentID = $student['studentID'];
$firstname = $student['firstname'];
$lastname = $student['lastname'];
$teacherID = $student['teacherID'];
// get teacher
$getTeacher = $link->prepare("SELECT * FROM teachers
WHERE teacherID = :teacherID");
$getTeacher->execute(array(
"teacherID" => $teacherID
));
$getTeacher = $getTeacher->fetchAll();
// loop through each teacher
foreach ($getTeacher as $teacher) {
$teacherFirstname = $teacher['firstname'];
$teacherLastname = $teacher['lastname'];
// output data
echo "
<tr>
<td><input type='text' name='studentID-$value' value='$studentID'></td>
<td><input type='text' name='firstname-$value' value='$firstname'></td>
<td><input type='text' name='lastname-$value' value='$lastname'></td>
<td><input type='text' name='teacherFirst-$value' value='$teacherFirstname'></td>
<td><input type='text' name='teacherLast-$value' value='$teacherLastname'></td>
</tr>
";
}
// add to row
$value += 1;
}
?>
</table>
<button type="submit" name="update">Update</button>
</form>
PHP Code that alters the db
$dataCount = 0;
foreach ($_POST as $data) {
if($dataCount % 5 === 0) {
echo "<br><br>";
echo $data . ", ";
} else {
echo $data . ", ";
}
$dataCount++;
}
What the form loops like on the screen
StudentID Firstname Lastname Teacher's Firstname Teacher's Lastname
_______________________________________________________________________________________
1 Bill Roy Jonathan Kung
2 Travis Roy Shanin Harnik
The easiest thing to do is use an array name in your input fields. This way your $_POST will be in a bunch of grouped arrays that are easily looped through:
<form action="server/edit/students.php" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Teacher's Firstname</th>
<th>Teacher's Lastname</th>
</tr>
<?php
// get student info
$getStudent = $link->prepare("SELECT * FROM students");
$getStudent->execute();
$getStudent = $getStudent->fetchAll(PDO::FETCH_ASSOC);
$value = 0; // counts rows
// loop through each student
foreach ($getStudent as $student) {
$studentID = $student['studentID'];
$firstname = $student['firstname'];
$lastname = $student['lastname'];
$teacherID = $student['teacherID'];
// get teacher
$getTeacher = $link->prepare("SELECT * FROM teachers WHERE teacherID = :teacherID");
$getTeacher->execute(array(
"teacherID" => $teacherID
));
$getTeacher = $getTeacher->fetchAll();
// loop through each teacher
foreach ($getTeacher as $teacher) {
$teacherFirstname = $teacher['firstname'];
$teacherLastname = $teacher['lastname'];
// output data
?>
<tr>
<td><input type='text' name='student[<?php echo $studentID ?>][firstname]' value='<?php echo $firstname ?>' /></td>
<td><input type='text' name='student[<?php echo $studentID ?>][lastname]' value='<?php echo $lastname ?>' /></td>
<td><input type='text' name='student[<?php echo $studentID ?>][teacherFirst]' value='<?php echo $teacherFirstname ?>' /></td>
<td><input type='text' name='student[<?php echo $studentID ?>][teacherLast]' value='<?php echo $teacherLastname ?>' /></td>
</tr>
<?php
}
// add to row
$value += 1;
}
?>
</table>
<button type="submit" name="update">Update</button>
</form>
When processing the $_POST you loop through the $_POST['student'] array and the keys will be the ids and the rest of the data is contained in the array.

Updating all rows at once in codeigniter, error in query

I am trying to update multiple rows simultaneously and I think my query is somewhat messed up while i am trying to update all my rows simultaneously. I am using CodeIgniter framework. I want to work on my query and the data being sent from the view but unable to get a logic to update all rows simultaneously. Please note that there should be only one update button as this is a requirement
My View code is:
<form action="" method="post">
<table border="1" style="background:none;width:100%;" RULES="ROWS" class="tab_data">
<thead>
<th width="30px">No</th>
<th >Action Item</th>
<th>Responsibility</th>
<th>Order</th>
<th>Mandatory?</th>
<th width = "100px" align="center">Actions</th>
</thead>
<tbody>
<?php
$serial_no = 1;
if(count($rows))
{
foreach($rows as $row)
{
?>
<tr>
<td><?php echo $serial_no; ?></td>
<td>
<?php
echo "<input type='hidden' class='col-md-4 form-control' name='checklist_id' value='"
.$row['checklist_id']."' />";
echo $row['action_item'];
?>
</td>
<td>
<?php echo $row['responsibility']; ?>
</td>
<td>
<input type="hidden" name="row_id[]" value="<?php echo $row['sequence']; ?>">
<input type="text" class="form-control" name="order[]" value="<?php echo $row['sequence']; ?>">
</td>
<td>
<input type="checkbox" class="" name="if_checklist<?php echo $row->checklist_id; ?>" value="1" echo 'checked'; >
</td>
<td align="center">
<?php
echo anchor('exits/delete_absconding_checklist/'.$row['checklist_id'],
"<i class='fa fa-trash-o' alt='Delete' title='Delete' rel='".$row['id']."' ></i>",
array('rel' => $row->id, 'class' => 'edit_row'));
?>
</td>
</tr>
<?php
$serial_no++;
}
}
?>
<tr>
<td></td><td></td><td></td><td></td>
<td>
<input type="hidden" name="action" value="update_order">
<button type="submit" name="submit" class="btn btn-info pull-right">Update</button>
</td>
</tr>
</tbody>
</table>
</form>
My Controller Code is:
function display_absconding_checklist()
{
if($this->input->post('action') == '_doDelete' || $this->input->post('action') == '_doChangeStatus')
{
$this->admin_init_elements->delete_rows('applicant_status');
}
if($this->input->post('action') == 'update_order')
{
$this->exit_common->update_absconding_checklist();
}
$data['rows'] = $this->exit_common->get_all_absconding_checklists();
$this->data['maincontent'] = $this->load->view('maincontents/backend_display_absconding_checklist', $data, true);
$this->load->view('layout', $this->data);
}
My Model code is:
function update_absconding_checklist($post_array)
{
$post_array = $this->input->post();
foreach($post_array['checklist_id'] as $key => $rowid)
{
if($rowid > 0)
{
if(isset($post_array['if_checklist'.$rowid]))
$in = '1';
else
$in = '0';
$sql1 = "UPDATE pr_absconding_checklists SET `action_item` = '"
.$post_array['action_item'][$key]
."', `sequence` = '".$post_array['sequence'][$key]
."', `if_checklist` = '".$in
."' WHERE `checklist_id` = ".$rowid;
}
else
{
$sql1 = "UPDATE pr_absconding_checklists SET `action_item` = '"
.$post_array['action_item'][$key]
."', `sequence` = '".$post_array['sequence'][$key]
."', `if_checklist` = '".$in."'";
}
$query1 = $this->db->query($sql1);
}
}
I am getting no errors but there are many errors in my code and i am messed up, i am attaching my table snapshot also, please recommend improvements
My Table name is pr_absconding_checklists

Want to update multiple records using checkboxes and save button

I am searching some records using two text boxes and then updating the selected records in database. i am able to see the value row id of the selected checkbox but when i want to get the value for updation in database it gives 0, i.e showing no record in array
Here is my code
if($_POST["search"])
{
$nitnumber = $_POST["nitnumber"];
$workno = $_POST["workno"];
$query = "select * from print where nit = $nitnumber and work = $work";
$result = mysql_query($query) or die ("<font color =red>NIT Number and/or Work Number is Missing</font>");
$count = mysql_num_rows($result);
if($count == 0)
echo "<font color=red>Record not found</font>";
else
{
while($record = mysql_fetch_assoc($result))
{
?>
<tr class="odd">
<td><div align="center"><?php echo $record['a']; ?></div></td>
<td><div align="center"><?php echo $record['b']; ?></div></td>
<td><div align="left"><?php echo $record['c']; ?></div></td>
<td> <div align="left">
<?php
enter code hereecho $record["d"];
?>
</td>
<td>
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>">
<?php echo $record["id"];?>
</td>
<?php } } }?>
<tr>
<td colspan="5" align="right"> <input type="submit" value="Save" name="save"> </td>
</tr>
<?php
if ($_POST['save'])
{
$num_chkboxes=count($_POST['checkbox']);
for($i=0; $i<$num_chkboxes; $i++){
$complete = intval($checkbox[$i]);
echo $complete;
var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
//$Result1 = mysql_query($updateSQL, $FamilyOrganizer) or die(mysql_error());
}
}
?>
<?php
if ($_POST['save'])
{
$checkbox1 = $_POST['chk1'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1)
{
$selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);
$updateSQL = "" // your update query here
}
?>
<input type="checkbox" name="chk1[]" value=""> // take checkboxes like this
First, the problem started when you fill the values of the checkboxes:
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>" />
you must gave them the value like
value="<?php echo $record['id'] ?>"
Second, you don't get the values of the checkboxes as you should:
for($i = 0; $i < count($_POST['checkbox']); $i++){
$complete = intval($_POST['checkbox'][$i]);
//echo $complete;
//var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
}
Another thing you should take care about is the assigning of the elements ids:
id="checkbox[]"
you must give unique ids for each element:
id="checkbox-1"
id="checkbox-2"

Dividing the One Column Data into Four Columns

I have 35 records of statename in mysql table. I have divided the data into two columns
Here is my php code for the requirement
<td>
<table class="statetable">
<?
//******Fetching State Name Dynamically*****//
$fetchstate = mysql_query("SELECT LocationName FROM servicedesklocationmaster group by LocationName ASC");
$half1 = floor(mysql_num_rows($fetchstate)/2);
echo $half1;
$count = 0;
// First Half State
while($count <= $half1 && $row = mysql_fetch_array($fetchstate))
{
$statename = $row['LocationName'];
$count++;
?>
<tr>
<td>
<font size="1.5">
<input type="checkbox" name="Location[]" id="Location" checked value="<?php echo $statename;?>" onClick="CheckEachAsset()"><?php echo $statename;?><br>
</font>
</td>
<?
}
//echo $count;
?>
</tr>
</table>
</td>
<td>
<table class="statetable">
<?
// Second Half State
while($row = mysql_fetch_array($fetchstate))
{
$statename = $row['LocationName'];
?>
<tr>
<td>
<font size="1.5">
<input type="checkbox" name="Location[]" id="Location"
checked value="<?php echo $statename;?>" onClick="CheckEachAsset()"><?php echo $statename;?><br>
</font>
</td>
<?
}
?>
</tr>
</table>
</td>
Now as per my new requirement i want to divide this into 4 columns can anybody suggest me
how to achieve it
$quater = floor(mysql_num_rows($fetchstate)/4);
$count = 0;
while($row = mysql_fetch_array($fetchstate)) {
if($count < $quater) {
// echo table content1
}
if($count >= $quater && $count < $quater*2) {
// echo table content2
}
if($count >= $quater*2 && $count < $quater*3) {
// echo table content3
}
if($count >= $quater*3 && $count < $quater*4) {
// echo table content4
}
$count++;
}
<td>
<table class="statetable">
<?
$fetchstate = mysql_query("SELECT LocationName FROM servicedesklocationmaster group by LocationName ASC");
$quart= floor(mysql_num_rows($fetchstate)/4);
echo $quart;
$count = 0;
$times=0;
while($times<=4 && $row = mysql_fetch_array($fetchstate))
{
$statename = $row['LocationName'];
$count++;
$times++;
?>
<tr>
<td>
<font size="1.5">
<input type="checkbox" name="Location[]" id="Location" checked value="<?php echo $statename;?>" onClick="CheckEachAsset()"><?php echo $statename;?><br>
</font>
</td>
<?
if($count==$quart && $times!=4){
$count=0;
?>
</tr>
</table>
</td>
<td>
<table class="statetable">
<?
}
}
//echo $count;
?>
</tr>
</table>
</td>

PHP/MYSQL. Updating multiple rows failing in the `for loop`

I have following HTML table:
<form method="post" action="update-table.php">
<table class="table-data" style="width: 960px;">
<thead>
<tr>
<td class="sorting" rowspan="1" colspan="1" style="width: 193px;">ID</td>
<td class="sorting" rowspan="1" colspan="1" style="width: 54px;">Live</td>
</tr>
</thead>
<tbody>
<tr class="odd">
<td class="nth-1"><input type="text" value="12" name="id"></td>
<td class="nth-2"><input type="checkbox" checked="checked" name="live"></td>
</tr>
<tr class="even">
<td class="nth-1"><input type="text" value="11" name="id"></td>
<td class="nth-2"><input type="checkbox" checked="checked" name="live"></td>
</tr>
<tr class="odd">
<td class="nth-1"><input type="text" value="10" name="id"></td>
<td class="nth-2"><input type="checkbox" checked="checked" name="live"></td>
</tr>
</tbody>
</table>
<input type="submit" />
and I'm trying to update live values accordingly to the ids with this file:
<?php
# update
session_name('users');
session_set_cookie_params(2*7*24*60*60);
session_start();
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
if(!$_SESSION['id']) {
header ("Location: index.php");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$id = clean($_POST['id']);
//$usr2 = $_SESSION['usr'];
$live = (isset($_POST['live']))?1:0;
//$updated = date("F j, Y, g:i a",time()+60*60);
//Create INSERT query
foreach ($display_order as $id => $live) {
$sql = "UPDATE news SET display_order = $live WHERE id = $id";
$result = mysql_query($sql);
if($result) {
//header("location: notes.php");
//exit();
print_r($sql);
print_r($display_order);
}else {
die("Query failed");
}
}
?>
But I'm getting an error:
Warning: Invalid argument supplied for foreach() in C:\Documents and Settings\USER\Desktop\Dropbox\wamp_at_work\update-table.php on line 33
Line 33 is: foreach ($display_order as $id => $live) {
What the problem? Any suggestions much appreciated.
The problem is that you're duplicating the 'name' attributes of the input elements. What you want to do is send arrays back to the server, ie:
Updated with extended answer:
<?php
$inp_orders = !empty($_POST['live']) ? $_POST['live'] : array();
// proccess post
if ($inp_orders)
{
foreach ($inp_orders as $id => $live) {
$id = (int) $id;
$live = (bool) $live;
// update orders
$sql = "UPDATE news SET display_order = $live WHERE id = $id";
$result = mysql_query($sql);
if($result) {
echo 'News updated';
}else {
die("Query failed");
}
}
}
// get orders from db
$res = mysql_select("SELECT * FROM news");
$view_orders = array();
while ($row = mysql_fetch_assoc($res))
{
$view_orders['id'] = $row['id'];
$view_orders['live'] = $row['live'];
}
?>
<form method="post" action="">
<table class="table-data" style="width: 960px;">
<thead>
<tr>
<td class="sorting" rowspan="1" colspan="1" style="width: 193px;">ID</td>
<td class="sorting" rowspan="1" colspan="1" style="width: 54px;">Live</td>
</tr>
</thead>
<tbody>
<?php foreach ($view_orders as $order): $id = (int) $order['id']; $odd = true; ?>
<tr class="<?php echo $odd ? 'odd' : 'even' ?>">
<td class="nth-1"><?php echo $id ?></td>
<td class="nth-2"><input type="checkbox" <?php echo $order['live'] ? 'checked="checked"' : '' ?> name="live[<?php echo $id ?>]" /></td>
</tr>
<?php $odd = $odd ? false : true; endforeach; ?>
</tbody>
</table>
<input type="submit" />
</form>
I'm going to assume people can not change the ID. So do this:
<td class="nth-2">
<input type="hidden" name="live[12]" value="0">
<input type="checkbox" name="live[12]" value="1" checked>
</td>
That will get you an array called $_POST['live'] with either 0 or 1 in it depending on if they clicked it.
The hidden field is because if they don't click it nothing at all is sent, which can be more difficult to parse, so first I send a 0, then overwrite it if the checkbox is checked.
If people can change the ID you'll need to modify it a bit. Leave a comment if so.

Categories