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
Related
currently I have created a system that can perform multiple delete actions for a list of data rows that fetch from a SQL database and display at dashboard_engineer.php. Each data row contains a delete button. Each row also has a checkbox that enables the user to delete selected data rows. At the bottom of the data rows, there's a button to delete all the selected data rows.
My problem is on multiple delete, lets say, if I select two data rows, (id 4 and 5) it will only delete one ID.
Below is my code
dashboard_engineer2.php
<?php
if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$team = $_REQUEST['team'];
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid
WHERE ot_report.status = 'yes' AND ot_users.team_id = :team AND report_date BETWEEN :from
AND :to ORDER BY ot_report.report_id DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindParam(':team', $team);
$sql->bindParam(':from', $from);
$sql->bindParam(':to', $to,);
$sql -> execute();
if($sql->rowCount() > 0){
echo'
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "10%"><input type="checkbox" id="checkAl"> All</th>
<th width = "3%">id</th>
<th width = "15%">Date</th>
<th width = "25%">Supervisor</th>
<th width = "30%">Task Name</th>
<th width = "10%">Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$status=$row['report_status'];
if($status=="Pending"){
$color="color:blue";
}
else {
$color="color:green";
}
$report_id = $row["report_id"];
echo'<tr>';
echo '<td><input type="checkbox" id="checkItem" name="check[]" value="'.$report_id.'"></td>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$row['report_date'].'</td>';
echo '<td>'.$row["fullname"].'</td>';
echo '<td>'.$row["task_name"].'</td>';
echo '<td align="center" style='.$color.'><strong>'.$status.'</strong></td>';
echo '<td align="center">';
echo '<form action = "view_task/view_task.php" method = "post" target="_blank">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-primary">View</button>';
echo '</form>';
echo '</td>';
echo '<td align="center">';
echo "<form action = 'remove2.php' method = 'post' onClick=\"return confirm('Do you want to remove this reports?')\">";
echo '<input type = "hidden" name = "from" value = "'.$from.'">';
echo '<input type = "hidden" name = "to" value = "'.$to.'">';
echo '<input type = "hidden" name = "team" value = "'.$team.'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Remove</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
$i++;
}
echo '<tr>';
echo '<td>';
echo "<form action = 'delete_selected.php' method = 'post'>";
echo '<input type="hidden" id="checkItem" name="check[]" value="'.$report_id.'">';
echo '<button type="submit" class="btn-danger btn-sm">DELETE</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
}
}
?>
delete_selected.php
<?php
include("../../../config/configPDO.php");
include("../../../config/check.php");
$checkbox = $_POST['check'];
for($i=0;$i<count($checkbox);$i++){
$report_id = $checkbox[$i];
$sql = "UPDATE ot_report SET status = 'no' WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php");
}
?>
Can anyone help me to solve this problem? Thanks
OK - the following is based upon the question's code but in order to build a working demo it has been generalised. The important thing here is the use of Javascript to maintain the list of IDs selected ( either by clicking the select-all checkbox or by clicking individual checkboxes. Please ignore the content generated in the form - the dates are spurious and meaningless to this example.
You could copy this and create a test page which should run OK - the PHP that generates the pseudo SQL is simply to display the statements that would be executed and not how it should be executed ( should be as per question, prepared statement )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( isset( $_POST['ids'] ) ){
$items=explode( ',', $_POST['ids'][0] );
foreach($items as $id){
$sql=sprintf('UPDATE ot_report SET status="no" WHERE report_id=%d',$id);
echo $sql . '<br />';
}
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<table>
<?php
for( $i=1; $i <= 10; $i++ ){
/* example data for dates... */
$hrs=mt_rand(1,24);
$mins=mt_rand(0,60);
$secs=mt_rand(0,60);
$month=mt_rand(1,12);
$day=mt_rand(1,28);
$year=mt_rand(2000,2020);
$from=date('y-m-d',mktime($hrs,$mins,$secs,$month,$day,$year));
$to=date('y-m-d',mktime($hrs+3,$mins+20,$secs,$month,$day,$year));
printf('
<tr>
<td><input type="checkbox" name="check[]" value="%1$d" /></td>
<td>Some data %1$d</td>
<td>
<form method="post">
<input type="hidden" name="from" value="%2$s" />
<input type="hidden" name="to" value="%3$s" />
<input type="hidden" name="id" value="%1$d" />
<input type="submit" />
</form>
</td>
</tr>', $i, $from, $to );
}
?>
</table>
<form method='post'>
<input type='checkbox' name='selectall' value='Select-All' />
<input type='hidden' name='ids[]' />
<input type='button' name='sub-delete' value='Update selected' />
</form>
<script>
let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
let tmp=[];
document.querySelector('[name="selectall"]').addEventListener('change',function(e){
let col=document.querySelectorAll('[name="check[]"]');
col.forEach(chk=>{
chk.checked=this.checked;
if( this.checked )tmp.push(chk.value)
else tmp.splice(tmp.indexOf(chk.value),1)
});
});
document.querySelectorAll('[name="check[]"]').forEach( chk=>{
chk.addEventListener('change',function(e){
if( this.checked )tmp.push(this.value)
else tmp.splice( tmp.indexOf(this.value),1);
});
});
document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
ids.value=tmp.join(',')
this.parentNode.submit()
});
</script>
</body>
</html>
Will generate something akin to:
UPDATE ot_report SET status="no" WHERE report_id=10
UPDATE ot_report SET status="no" WHERE report_id=8
UPDATE ot_report SET status="no" WHERE report_id=6
UPDATE ot_report SET status="no" WHERE report_id=4
Quickly trying to adapt this example with your code :
<?php
if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
$from=$_REQUEST['from'];
$to =$_REQUEST['to'];
$team=$_REQUEST['team'];
$result='';
$query="SELECT * FROM ot_report
LEFT JOIN ot_users ON ot_report.badgeid=ot_users.badgeid
WHERE ot_report.status='yes' AND ot_users.team_id=:team AND report_date BETWEEN :from AND :to
ORDER BY ot_report.report_id DESC";
$sql=$conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindParam(':team', $team);
$sql->bindParam(':from', $from);
$sql->bindParam(':to', $to);
$sql->execute();
if($sql->rowCount() > 0){
echo'
<table class="table-bordered" width="100%">
<thead>
<tr>
<th width="10%"><input type="hidden" name="selectall" value="Select-All">All</th>
<th width="3%">id</th>
<th width="15%">Date</th>
<th width="25%">Supervisor</th>
<th width="30%">Task Name</th>
<th width="10%">Status</th>
<th colspan="2" width="7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row=$sql->fetch(PDO::FETCH_ASSOC)){
$status=$row['report_status'];
if($status=="Pending"){
$color="color:blue";
} else {
$color="color:green";
}
$report_id=$row["report_id"];
echo'
<tr>
<td><input type="checkbox" name="check[]" value="'.$report_id.'"></td>
<td>'.$report_id.'</td>
<td>'.$row['report_date'].'</td>
<td>'.$row["fullname"].'</td>
<td>'.$row["task_name"].'</td>
<td align="center" style='.$color.'><strong>'.$status.'</strong></td>
<td align="center">
<form action="view_task/view_task.php" method="post" target="_blank">
<input type="hidden" name="report_id" value="'.$report_id.'">
<button type="submit" class="btn-primary">View</button>
</form>
</td>
<td align="center">
<form action="remove2.php" method="post" onsubmit="return confirm(\'Do you want to remove this reports?\')">
<input type="hidden" name="from" value="'.$from.'">
<input type="hidden" name="to" value="'.$to.'">
<input type="hidden" name="team" value="'.$team.'">
<input type="hidden" name="report_id" value="'.$report_id.'">
<button type="submit" class="btn-danger">Remove</button>
</form>
</td>
</tr>';
$i++;
}
echo '
<tr>
<td>
<form action="delete_selected.php" method="post">
<input type='hidden' name='ids[]' />
<input type='button' name='sub-delete' value='DELETE' />
</form>
</td>
</tr>';
}
}
?>
<script>
let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
let tmp=[];
document.querySelector('[name="selectall"]').addEventListener('change',function(e){
let col=document.querySelectorAll('[name="check[]"]');
col.forEach(chk=>{
chk.checked=this.checked;
if( this.checked )tmp.push(chk.value)
else tmp.splice(tmp.indexOf(chk.value),1)
});
});
document.querySelectorAll('[name="check[]"]').forEach( chk=>{
chk.addEventListener('change',function(e){
if( this.checked )tmp.push(this.value)
else tmp.splice( tmp.indexOf(this.value),1);
});
});
document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
ids.value=tmp.join(',')
this.parentNode.submit()
});
</script>
and
delete_selected.php
<?php
include("../../../config/configPDO.php");
include("../../../config/check.php");
$checkbox=explode( ',', $_POST['ids'][0] );
for($i=0;$i < count($checkbox); $i++){
$report_id=$checkbox[$i];
$sql="UPDATE ot_report SET status='no' WHERE report_id=:report_id";
$query=$conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php");
}
?>
I have problem with my buttons. I will try to explain.
1)I have users db from postgresql and new db in ms sql.
2)Created site with 2 columns in table ("SELECT * from users"-postgresql ): They are id/user
3)Then added new column "Operator" which contain submit buttons and functionality of submit buttons is updating "access" column from ms sql db.
PROBLEM:
It prints all buttons for all data that I have in ms sql(I have 7 rows data in ms sql, it prints 7 buttons for each row), I need to "echo" 1 button for each row which will be changable. If access==1 it should be named Active , else it should be named Diactive.
Here is my code and picture of what I got:
<?php
<table class="table table-condensed">
<thead>
<tr>
<th>ID</th>
<th>User</th>
<th>Operator</th>
<th>View</th>
</tr>
<?php
while ($row = pg_fetch_array($result)) {
?>
<tr>
<td>
<?php
$id = $row["id"];
echo $id;
?>
</td>
<td>
<?php
$username = $row["username"];
echo $username;
?>
</td>
<td>
<form method="POST" action="oper.php">
<?php
include ("db.php");
$result2 = pg_query($db_connection, "SELECT * from users ORDER by id asc");
while ($row1 = pg_fetch_array($result2))
{
$iddrain= $row1['id'];
//echo $iddrain;
//echo $iddrain;
$q7= "Select access from nezeret where id_m=$iddrain";
//var_dump($q7);
$resultid= sqlsrv_query($link, $q7, $params, $options);
while($row7= sqlsrv_fetch_array($resultid))
{
//$rs7=$row7['ID_M'];
$rs8=$row7['access'];
//echo $rs8;
//break;
if($rs8==1)
{
echo "<p><input type=\"submit\" name=\"uid\" value=Operator-ON onchange=\"this.form.submit()\"></p>
<p><input type=\"hidden\" name=\"uid\" value=$id onchange=\"this.form.submit()\"></p>";
}
else
{
echo "<p><input type=\"submit\" name=\"uid\" value=DIavtive onchange=\"this.form.submit()\"></p>
<p><input type=\"hidden\" name=\"uid\" value=$id onchange=\"this.form.submit()\"></p>";
}
}
}
?>
</form>
</td>
<?php
}
?>
</tr>
</table>
?>
You are doing typo mistake na dnot giving quote for value attributes near :
try like this :
if($rs8==1)
{
echo '<p><input type="submit" name="uid" value="Operator-ON" onchange="this.form.submit()"></p>
<p><input type="hidden" name="uid" value="'.$id.'" onchange=
"this.form.submit()"></p>';
}
else
{
echo '<p><input type="submit" name="uid" value="DIavtive" onchange="this.form.submit()"></p>
<p><input type="hidden" name="uid" value="'.$id.' onchange="this.form.submit()"></p>';
}
}
I have reditted your code to remove some errors that were making it fail to work;
<?php include ("db.php"); ?>
<table class="table table-condensed">
<thead>
<tr>
<th>ID</th>
<th>User</th>
<th>Operator</th>
<th>View</th>
</tr>
</thead>
<?php
//while ($row = pg_fetch_array($result)) {
<?php foreach( pg_fetch_array($result) as $row ) { ?>
?>
<tbody>
<tr>
<td<?php echo $row['id'] ?></td>
<td><?php echo $row['username'] ?></td>
<td>
<form method="POST" action="oper.php">
<?php
$result2 = pg_query($db_connection, 'SELECT * from users ORDER by id asc');
while ($row1 = pg_fetch_array($result2)) {
$iddrain = $row1['id'];
$q7 = "Select access from nezeret where id_m=$iddrain";
//var_dump($q7);
$resultid = sqlsrv_query($link, $q7, $params, $options);
while ($row7 = sqlsrv_fetch_array($resultid)) {
//$rs7=$row7['ID_M'];
$rs8 = $row7['access'];
if ($rs8 == 1) {
echo '<p><input type="submit" name="uid" value=Operator-ON onchange="this.form.submit()"></p>
<p><input type="hidden" name="uid" value=$id onchange="this.form.submit()"></p>';
} else {
echo '<p><input type="submit" name="uid" value=DIavtive onchange="this.form.submit()"></p>
<p><input type="hidden" name="uid" value=$id onchange="this.form.submit()"></p>';
}
}
}
?>
</form>
</td>
</tr>
</tbody>
</table>
I`ve changed code and now it is working, problem was additional useless fetch. Here is the code:
<table class="table table-condensed">
<thead>
<tr>
<th>ID</th>
<th>User</th>
<th>Operator</th>
</tr>
<?php
while ($row = pg_fetch_array($result)) {
?>
<tr>
<td>
<?php
$id = $row["id"];
echo $id;
?>
</td>
<td>
<?php
$username = $row["username"];
echo $username;
?>
</td>
<td>
<form method="POST" action="oper.php">
<?php
include ("db.php");
$iddrain= $row['id'];
$q7= "Select * from nezeret where id_m=$iddrain";
//var_dump($q7);
$resultid= sqlsrv_query($link, $q7, $params, $options);
while($row7= sqlsrv_fetch_array($resultid))
{
$rs8=$row7['access'];
//echo $rs8;
if($rs8==1)
{
echo "<p><input type=\"submit\" name=\"uid\" value=Operator onchange=\"this.form.submit()\"></p>
<p><input type=\"hidden\" name=\"uid\" value=$id onchange=\"this.form.submit()\"></p>";
}
else
{
echo "<p><input type=\"submit\" name=\"uid\" value=Nazeret onchange=\"this.form.submit()\"></p>
<p><input type=\"hidden\" name=\"uid\" value=$id onchange=\"this.form.submit()\"></p>";
}
}
?>
</form>
</td>
</tr>
<?php
}
?>
</tr>
</table>
i have created one edit form that i am editing my room number and room description and room image etc . based on the category id.
first edit form will fetch the data from database .
example code :
if (isset($_GET['id']))
{
$current_id = $_GET['id'];
$query=mysql_query("select * from room where room_id='$current_id'");
$i = 0;
while($row=mysql_fetch_array($query))
{
$i++;
$room_id=$row['room_id'];
$cat_id=$row['cat_id'];
$room_number=$row['room_no'];
$room_desc=$row['room_desc'];
$room_image=$row['room_image'];
?>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Room Id</th>
<th>Category Type</th>
<th>Room Number</th>
<th>Room Description</th>
<th>Room Image</th>
</tr>
</thead>
<tbody>
<tr class="active">
<td><input type="text" value="<?php echo $room_id; ?>" readonly="readonly" name="room_id"></td>
<td>
<?php
// Slecting cat_id for displaying cat_type on Edit form
$query_room=mysql_query("SELECT * FROM `category` WHERE cat_id in (". $cat_id .")");
while($row=mysql_fetch_array($query_room))
{
$category_name=$row['cat_type'];
$category_id=$row['cat_id'];
echo '<input type="text" value='.$category_name.' readonly="readonly" name="cat_name">';
echo '<input type="hidden" value='.$category_id.' readonly="readonly" name="cat_id">'; // hidden value for cat_id to fetch data from category
$_SESSION['imagesession'] = "data:image/png;base64, base64_encode($room_image)";
}
?>
</td>
<td><input type="text" value="<?php echo $room_number ;?>" name="room_number" required></td>
<td><input type="text" value="<?php echo $room_desc ;?>" name="room_desc" required></td>
<td><input type="image" src="data:image/png;base64,<?php echo base64_encode($room_image);?>" name="myimage" alt="No Photo" title="Click to View in Detail" height="50px" width="50px"/>
<label>Upload Image</label>
<input type="file" id="uploadImage" value="<?php echo base64_encode($room_image);?>" name="image" onChange="PreviewImage();" />
<img id="uploadPreview" style="width: 200px; height: 300px; border-style:none" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<button type="submit" class="btn btn-success" name="update_rooms">Update Rooms</button>
<button type="reset" class="btn btn-danger">Reset</button>
</form>
Getting data and updating in database
if(isset($_POST['update_rooms']))
{
$current_id = $_POST['room_id'];
$room_desc = $_POST['room_desc'];
$room_number = $_POST['room_number'];
$cat_id = $_POST['cat_id'];
// $imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
if(empty($imageData))
{
if($imageData === $existing_category_image)
{
echo '<span style="color:#E02F2F;text-align:center;font-size:30px;padding-left:190px;">Reselect the Image</span>';
return;
}
}
$sql = "UPDATE room SET cat_id='$cat_id', room_no='$room_number', room_desc='$room_desc', room_image='$imageData' WHERE room_id='$current_id'";
//echo "Res".$sql;
$result=mysql_query($sql);
if($result)
{
echo '<span style="color:#E02F2F;text-align:center;font-size:30px;padding-left:190px;">Record Updated Successfully!</span>';
//header("Location: success.php");
} else
{
echo '<span style="color:#E02F2F;text-align:center;font-size:30px;padding-left:250px;">Error Found!.mysql_error()</span>';
}
}
PROBLEM:
1.while editing all fields are updating successfully but come to the image its not working i mean if user is adding new image then its updating in database but if user is editing existing image then null value is storing in database .
how to solve this problem . how to send dynamic value in input type file . any help ?
you may also use this
Fetch this $existing_category_image from database no need to post it from form.
if($imageData == '' || $imageData == null){
$sql = "UPDATE room SET cat_id='$cat_id', room_no='$room_number', room_desc='$room_desc' WHERE room_id='$current_id'";
}else{
$sql = "UPDATE room SET cat_id='$cat_id', room_no='$room_number', room_desc='$room_desc', room_image='$imageData' WHERE room_id='$current_id'";
}
OR
Write this:
if($imageData == '' || $imageData == null){
$imageData = $existing_category_image;
}
before
$sql = "UPDATE room SET cat_id='$cat_id', room_no='$room_number', room_desc='$room_desc', room_image='$imageData' WHERE room_id='$current_id'";
Good day. I want to delete selected item by the user. But it turns out what ever button clicked by user, the first data row is deleting. Im stuck here. Please help.
This is my code:
HTML
<form method="POST" action="<?php $_PHP_SELF ?>">
<?php
$query = "select * from tblsr";
$request = mysql_query($query)or die(mysql_error());?>
<table class="table table-hover">
<tr>
<th>Softwares</th>
<th>Difficulty</th>
<th></th>
<th></th>
</tr>
<?php while($row = mysql_fetch_array($request)){
?>
<tbody>
<tr class="success">
<td><?php echo $row['Software']; ?></td>
<td><?php echo $row['Difficulty']; ?></td>
<td><input type="submit" class="btn btn-sm btn-success" name="change" value="Change Difficulty"/></td>
<td><input type="submit" class="btn btn-sm btn-danger" name="remove" value="Delete"/></td>
<input type="hidden" name="id[]" value="<?php echo $row['id']; ?>"/>
</tr>
</tbody>
<?php
}
?> </form>
DELETE Query
if(isset($_POST['remove'])){
$count = count($_POST['id']); //get total number of array element
for ($i = 0; $i < $count; $i++) {
$id = $_POST['id'][$i];
$sql = "Delete FROM tblsr
Where id = '$id'";
$success = mysql_query($sql) or die (mysql_error());
mysql_close();
if ($success == TRUE){
?>
<script>
alert('Deleted.');
window.location.href='manageRequest.php';
</script>
<?php
}
}
}
Your code's problem is that you never increase $i ( $i++ ) , and always your delete query affect on the first row ( id ) . you can put $i++ in your while loop to fix it, but I recommend that you simply do like below and don't bother yourself with a loop.
Delete query :
$rm = $_POST['id'];
if (isset($_POST['remove'])) {
foreach ($rm as $key => $value) {
$rm[$key] = "'".$value."'";
}
$sql = "Delete FROM tblsr
Where id IN(" . implode(",", $rm) .")";
die($sql);
$success = mysql_query($sql) or die(mysql_error());
if ($success) {
?>
<script>
alert('Deleted.');
window.location.href = 'manageRequest.php';
</script>
<?php
}
}
your form example for delete users:
<form method="POST" action="<?php $_PHP_SELF ?>">
<?php
$query = "select * from tblsr";
$request = mysql_query($query) or die(mysql_error());
?>
<table class="table table-hover">
<tr>
<th>Softwares</th>
<th>Difficulty</th>
<th></th>
<th></th>
</tr>
<?php
while ($row = mysql_fetch_array($request)) {
?>
<tbody>
<tr class="success">
<td><?php echo $row['Software']; ?></td>
<td><?php echo $row['Difficulty']; ?></td>
<td>
<input type="checkbox" name="id[]" value="<?php echo $row['id']; ?>"/>
delete
</td>
</tr>
</tbody>
<?php
}
?>
</table>
<button type="submit" name="remove" class="btn btn-success">
delete checked user
</button>
</form>
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.