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

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.

Related

I get the data from mysql checkboxed it and send it back to mysql the records saves for only one student with id no 3

I get the data from mysql and display it in the table now i'm trying to send it to the database for each student by checking the checkbox, then what should i do to send all table data into the msql database with the different student id
<form class="col-md-12" action="Attendance.php" method="post">
<table id="example" class="myclass table table-striped" />
<thead>
<tr>
<th>ID</th>
<th>Full Name</th>
<th>Father Name</th>
<th><label><input type="checkbox" id="selectAll" name="chbox[]"> All Present </label></th>
</tr>
</thead>
<tbody>
<?php
$SrNo = 0;
global $dbManager;
$sql = "SELECT * FROM studentinfo";
$stmt = $dbManager->query($sql);
while($DataRows = $stmt->fetch()){
$RollNo = $DataRows['id'];
$FullName = $DataRows['fullname'];
$FatherName = $DataRows['fathername'];
?>
<tr>
<td><?php echo $RollNo; ?></td>
<td><?php echo $FullName; ?></td>
<td><?php echo $FatherName; ?></td>
<td><input type="checkbox" name="chbox[]" value="1" /></td>
</tr>
</tbody>
<?php } ?>
<tfoot>
<?php
if(isset($_POST['Submit'])){
$StudentRollNo = $RollNo;
$Attendance = $_POST['chbox'];
// date_default_timezone_set("Asia/Kabul");
$CurrentTime = time();
$DateTime = strftime("%B-%d-%Y %H:%M:%S", $CurrentTime);
if(empty($Attendance)){
$_SESSION['ErrorMessage'] = "Please filled all fields";
RedirectTo("Attendance.php");
}
else{
// the sql code is here.
global $dbManager;
foreach ($Attendance as $key => $value) {
$sql = "INSERT INTO attendance(sid, subjectid, classid, attendance, datetime) VALUES(:studentId,'1','2', :attendancE, :dateTime)";
$stmt = $dbManager->prepare($sql);
$stmt->bindValue(':studentId',$StudentRollNo);
$stmt->bindValue(':attendancE',$value);
$stmt->bindValue(':dateTime',$DateTime);
$Execute = $stmt->execute();
if($Execute){
$_SESSION['SuccessMessage'] = "Attendance Submited Successfully.";
RedirectTo("Attendance.php");
}
else{
$_SESSION['ErrorMessage'] = "Something went wrong. Try Again!";
RedirectTo("Attendance.php");
}
}
}
?>
<tr>
<td>
<i class="fa fa-check"></i>
<input type="submit" name="Submit" value="Save Attendance">
</td>
</tr>
</tfoot>
</table>
</form>
Mysql database: the problem is that the record saves only for one student.
Bring you table inside the while loop where you are fetching the values from the database and then assign the value of students dynamically for the checkbox value
you can do
value="<?php echo $RollNo; ?>";
just like you echo out the other values add the echo into the value field of the checkbox in order to get the values dynamically assigned to each checkbox

Why I can't keep my session when I register

customer_register.php
<?php
session_start();
?>
<form action="customer_register.php" method="post" enctype="multipart/form-data">
<?php
if (isset($_POST['c_name']) && isset($_POST['c_email']) && isset($_POST['c_usrname']) && isset($_POST['c_password']) && isset($_POST['c_country']) && isset($_POST['c_city']) && isset($_POST['c_contact']) && isset($_POST['c_address']) && isset($_FILES['c_image']['name'])) {
$c_ip_add = getIp();
$c_name = $_POST['c_name'];
$c_email = $_POST['c_email'];
$c_username = $_POST['c_usrname'];
$c_password = $_POST['c_password'];
$c_country = $_POST['c_country'];
$c_city = $_POST['c_city'];
$c_contact = $_POST['c_contact'];
$c_address = $_POST['c_address'];
$c_image = #$_FILES['c_image']['name'];
$c_tmp_name = #$_FILES['c_image']['tmp_name'];
$location = 'customer/customer_images/';
if (!empty($c_name) && !empty($c_email) && !empty($c_username) && !empty($c_password) && !empty($c_country) && !empty($c_city) && !empty($c_contact) && !empty($c_address) && !empty($c_image)) {
move_uploaded_file($c_tmp_name, $location.$c_image);
$select_user = "SELECT customers_username FROM customers WHERE customers_username = '$c_username'";
$run_select_user = mysqli_query($conn, $select_user);
if (mysqli_num_rows($run_select_user) == NULL) {
$insert_customer = "INSERT INTO customers(customers_ip, customers_name, customers_email, customers_username, customers_pass, customers_country, customers_city, customers_contact, customers_address, customers_image) VALUES ('$c_ip_add', '$c_name', '$c_email', '$c_username', '$c_password', '$c_country', '$c_city', '$c_contact', '$c_address', '$c_image')";
$run_insert_customer = mysqli_query($conn, $insert_customer);
$select_cart = "SELECT * FROM cart WHERE ip_add = '$c_ip_add'";
$run_select_cart = mysqli_query($conn, $select_cart);
$check_cart = mysqli_num_rows($run_select_cart);
if ($check_cart == 0) {
$_SESSION['customer_email'] = $c_email;
$_SESSION['username'] = $c_username;
echo '<script>alert("Account has been successfully created")</script>';
echo '<script>window.open("customer/my_account.php","_self")</script>';
} else {
$_SESSION['customer_email'] = $c_email;
$_SESSION['username'] = $c_username;
echo '<script>alert("Account has been successfully created")</script>';
echo '<script>window.open("checkout.php","_self")</script>';
}
} else {
echo "<div align='center' style='color:white; font-size:20px; padding:20px 0px;'><b>The Username already exists. Please try another username.</b></div>";
}
} else {
echo "<div align='center' style='color:white; font-size:20px; padding:20px 0px;'><b>All Fileds are required</b></div>";
}
}
?>
<table align="center" width="750">
<thead>
<tr align="center">
<th colspan="3"><h1>Create an Account</h1></th>
</tr>
</thead>
<tbody>
<tr>
<td id="label" align="right">Name:</td>
<td><input type="text" name="c_name" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Email:</td>
<td><input type="text" name="c_email" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Username:</td>
<td><input type="text" name="c_usrname" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Password:</td>
<td><input type="password" name="c_password" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Image:</td>
<td><input type="file" name="c_image" required></td>
</tr>
<tr>
<td id="label" align="right">Country:</td>
<td>
<select name="c_country">
<option size="50">Select Country</option>
<?php countries(); ?>
</select>
</td>
</tr>
<tr>
<td id="label" align="right">City:</td>
<td><input type="text" name="c_city" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Contact:</td>
<td><input type="text" name="c_contact" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Address:</td>
<td><input type="text" name="c_address" size="40" required></td>
</tr>
<tr align="center">
<td colspan="3"><input type="submit" name="register" value="Create Account"></td>
</tr>
</tbody>
</table>
</form>
customer_login.php
<?php
session_start();
?>
<form method="post" action="">
<table width="500" align="center" bgcolor="skyblue">
<thead>
<tr align="center">
<th colspan="4"><h2>Login or Register to Buy!</h2></th>
</tr>
</thead>
<tbody>
<tr>
<td align="right"><b>Email:</b></td>
<td><input type="text" name="email" placeholder="Enter Email"></td>
</tr>
<tr>
<td align="right"><b>Password:</b></td>
<td><input type="password" name="pass" placeholder="Enter Password"></td>
</tr>
<tr align="center">
<td colspan="4">Forgot Password?</td>
</tr>
<tr align="center">
<td colspan="3"><input type="submit" name="login" value="Login"></td>
</tr>
</tbody>
</table>
<h2 style="float:right; padding:10px;">New? Register Here</h2>
</form>
<?php
if (isset($_POST['email']) && isset($_POST['pass'])) {
$email = $_POST['email'];
$pass = $_POST['pass'];
if (!empty($email) && !empty($pass)) {
$select_id = "SELECT * FROM customers WHERE customers_email = '$email' AND customers_pass = '$pass'";
$run_select_id = mysqli_query($conn, $select_id);
foreach ($run_select_id as $details) {
$usrname = $details['customers_username'];
$id = $details['customers_id'];
}
$num_run_select = mysqli_num_rows($run_select_id);
if ($num_run_select == NULL) {
echo '<script>alert("Invalid : Email/Password combination")</script>';
exit();
}
$c_ip_add = getIp();
$select_cart = "SELECT * FROM cart WHERE ip_add = '$c_ip_add'";
$run_select_cart = mysqli_query($conn, $select_cart);
$check_cart = mysqli_num_rows($run_select_cart);
if ($num_run_select > 0 AND $check_cart == 0) {
$_SESSION['customer_email'] = $email;
$_SESSION['username'] = $usrname;
$_SESSION['id'] = $id;
echo "<script>alert('You Have Logged In Succesfully')</script>";
echo "<script>window.open('customer/my_account.php','_self')</script>";
exit();
} else {
$_SESSION['customer_email'] = $email;
$_SESSION['username'] = $usrname;
$_SESSION['id'] = $id;
echo "<script>alert('You Have Logged In Succesfully')</script>";
echo "<script>window.open('checkout.php','_self')</script>";
}
} else {
echo 'Please enter valid email ID';
}
}
?>
my_account.php
<?php
session_start();
?>
<ul id="categories">
<?php
$location = 'customer_images/';
$usr_email = $_SESSION['customer_email'];
$user_name = #$_SESSION['username'];
$usr_id = $_SESSION['id'];
$select_image = "SELECT * FROM customers WHERE customers_id = '$usr_id'";
$run_image = mysqli_query($conn,$select_image);
foreach ($run_image as $select_all_data) {
$id = $select_all_data['customers_id'];
$name = $select_all_data['customers_name'];
$username = $select_all_data['customers_username'];
$email = $select_all_data['customers_email'];
$country = $select_all_data['customers_country'];
$city = $select_all_data['customers_city'];
$contact = $select_all_data['customers_contact'];
$address = $select_all_data['customers_address'];
$image = $select_all_data['customers_image'];
echo "<li style=''><img src='$location$image' height='150' width='174' style='text-align:center; border:3px solid black; padding:4px; border-radius: 109px;'></li>";
}
?>
<li>My Orders</li>
<li>Edit Account</li>
<li>Change Password</li>
<li>Delete Account</li>
<li>Logout</li>
</ul>
</div>
<div class="content_area2">
<?php cart(); ?>
<div id="my_account_menu">
<span>
<?php
if (isset($_SESSION['customer_email'])) {
echo "Welcome <i style='color:orange;'>" . $_SESSION['username']. ' </i>';
}
?>
<?php
if (!isset($_SESSION['customer_email'])) {
echo "<a href='../checkout.php' style='color:white;'>Login</a>";
} else {
echo "<a href='../logout.php' style='color:orange;'>Logout</a>";
}
?>
</span>
</div>
<?php getIp(); ?>
<div id="products_box">
<?php
if (!isset($_GET['my_orders']) && !isset($_GET['edit_account']) && !isset($_GET['change_pass']) && !isset($_GET['delete_account'])) {
?>
<div style="text-align:center;">
<table>
<tbody>
<tr>
<td id="label">Name : </td>
<td id="detail"><?php echo #$name; ?></td>
</tr>
<tr>
<td id="label">Username (Display Name) : </td>
<td id="detail"><?php echo #$username; ?></td>
</tr>
<tr>
<td id="label">Email : </td>
<td id="detail"><?php echo #$email; ?></td>
</tr>
<tr>
<td id="label">City : </td>
<td id="detail"><?php echo #$city; ?></td>
</tr>
<tr>
<td id="label">Contact : </td>
<td id="detail"><?php echo #$contact; ?></td>
</tr>
<tr>
<td id="label">Address : </td>
<td id="detail"><?php echo #$address; ?></td>
</tr>
</tbody>
</table>
</div>
<div style="padding:20px;"><b>You can see your orders by clicking this link</b></div>
<?php
}
?>
The problem is when I login it is working fine but when I register the user it gives the error undefined
$usr_id = $_SESSION['id'];
in my_account.php and all the information about the user is not displayed
I HAVE STARTED THE SESSION
I think you forget to call session_start before to do anything, even when there is no existing session.
<?php
session_start()
// your code...
You may want to look how it works with the basic example from the session_start function
As stated within the PHP session_start documentation:
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
So you may want to include this call after PHP opening tag <?php as I wrote above
You have to initiate the session by using session_start() on every page where you want to use the session. And this is missing on my_account.php
Ex:
<?php
session_start();
// your code
nowhere in your customer_register.php file do you actually set $_SESSION['id'].
in addition to this:
there are no form tags around your register form, so its hard to see how any data is getting into the script anyway.
your'e also silencing (#) errors. If this is a learning task, which from your comments I assume it is, thats a very counterproductive thing to do.
As you only set $_SESSION['id'] in the login handing script, its not going to be available across pages unless they go through that form. Its hard to tell from your code what your'e intended user journey is, but as it stands at the moment it looks like your'e expecting them to register, then be able to see the account page as a logged in user.
Just set $_SESSION['id'] in the register script, or dispense with it entirely and use the username (seeing as you validate it as unique anyway).
Also, your'e query in the my_account.php is looking for a column customer_id which (as far as I can see) you dont actually set in the insert statement.
This is the trouble with programming, it only does what you tell it to do.

Can you update in a div tag

I have a little question about something. I have some forms, where I send the input to a MySQL database. I get the return from the database, out in some div tags. Here I have 2 buttons. Button number 1 can delete the row, and button number 2 should have a function, where I can update a specific row, if I want to change the content of the row. But can I update a div tag? I can see on the net, that a lot of people use tables to do that.
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/arrangeTables.css">
</head>
<body>
<?php
include 'connection.php';
if(isset($_POST['addto'])){
// Insert to database
$date = $_POST['date'];
$day = $_POST['day'];
$fromtime = $_POST['fromtime'];
$totime = $_POST['totime'];
$sql = "INSERT INTO addWorkTime(date, day, fromtime, totime) VALUES('$date', '$day', '$fromtime', '$totime')";
$result = mysql_query($sql, $dbhandle) or die(mysql_error($dbhandle));
// Update of the row
if(isset($_POST['update'])){
$hidden = mysql_real_escape_string($_POST['hidden']);
$UpdateQuery = "UPDATE addWorkTime
SET date='$_POST[date]',
day='$_POST[day]',
fromtime='$_POST[fromtime]',
totime='$_POST[totime]'
WHERE p_id='$_POST[hidden]'";
$update = mysql_query($UpdateQuery, $dbhandle) or die(mysql_error($dbhandle));
if($update) {
echo "Succes";
} else {
echo "Der er en fejl";
}
}; // brace for if(isset($_POST['update']))
if($result){
echo "Insert successful.";
}
}; // brace for if(isset($_POST['addto']))
if(isset($_POST['delete'])){
$hidden = mysql_real_escape_string($_POST['hidden']);
$DeleteQuery = "DELETE FROM addWorkTime WHERE p_id=$hidden";
$delete = mysql_query($DeleteQuery, $dbhandle) or die(mysql_error($dbhandle));
if($delete){
echo "Delete successful";
}
}
//Return records from database
$result = mysql_query("SELECT p_id, date, day, fromtime, totime FROM addWorkTime");
?>
<form method="post">
<h3>Add your worktime to database</h3><br>
Date:
<input type="date" name="date"><br><br>
Day
<select name="day">
<option value="Mandag">Mandag</option>
<option value="Tirsdag">Tirsdag</option>
<option value="Onsdag">Onsdag</option>
<option value="Torsdag">Torsdag</option>
<option value="Fredag">Fredag</option>
<option value="Lørdag">Lørdag</option>
<option value="Søndag">Søndag</option>
</select>
From time:
<input type="time" name="fromtime">
To time:
<input type="time" name="totime">
<input type="submit" name="addto" value="submit"><br><br>
<!-- Return from the database -->
<h3>Return from database:</h3><br>
<!-- headers -->
<table>
<tr>
<th class="column0">Primary Key</th>
<th class="column1">Date</th>
<th class="column2">Day</th>
<th class="column3">From</th>
<th class="column4">To</th>
</tr>
</table>
</form>
<!--loop through through the database -->
<?php while($row = mysql_fetch_array($result)): ?>
<form method="post">
<table>
<tr>
<td class="resultcolumn0"><?php echo $row{'p_id'};?></td>
<td class="resultcolumn1"><?php echo $row{'date'};?><br></td>
<td class="resultcolumn2"><?php echo $row{'day'};?></td>
<td class="resultcolumn3"><?php echo $row{'fromtime'};?></td>
<td class="resultcolumn4"><?php echo $row{'totime'};?></td>
<td><input type="hidden" name="hidden" value="<?php echo $row{'p_id'}?>"><?php echo $row{'p_id'}?></td>
<td><input type="submit" name="update" value="Update"></td>
<td><input type="submit" name="delete" value="Delete"></td>
</tr>
</table>
</form>
<?php endwhile; ?>
</body>
</html>
If you want to update your cell table like your recording, you can do a tricky way like this code snippet:
function change1() {
var inp1 = document.getElementById('myTable').rows[1].cells[0];
inp1.innerHTML = "<input type='text' name='inp1'>";
var inp2 = document.getElementById('myTable').rows[1].cells[1];
inp2.innerHTML = "<input type='text' name='inp2'>";
}
function change2() {
var inp1 = document.getElementById('myTable').rows[2].cells[0];
inp1.innerHTML = "<input type='text' name='inp1'>";
var inp2 = document.getElementById('myTable').rows[2].cells[1];
inp2.innerHTML = "<input type='text' name='inp2'>";
}
table, td {
border: 1px solid black;
}
<table id="myTable">
<tr>
<td>column 1</td>
<td>column 2</td>
<td>action</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
<td>
<button onclick="change1()">Update</button>
</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
<td>
<button onclick="change2()">Update</button>
</td>
</tr>
</table>
<button onclick="alert('whatever function to save the edit')">Save</button>
you can improve that to give <form> tag to your <table> tag and save that using another Save button. Or you can use if conditional to your update button for change to textfield and post it to your database.
<form method="post" action='function_to_update_or_delete.php'>
<table>
<tr>
<td class="resultcolumn0"><?php echo $row{'p_id'};?></td>
<td class="resultcolumn1"><?php echo $row{'date'};?><br></td>
<td class="resultcolumn2"><?php echo $row{'day'};?></td>
<td class="resultcolumn3"><?php echo $row{'fromtime'};?></td>
<td class="resultcolumn4"><?php echo $row{'totime'};?></td>
<td><input type="hidden" name="hidden" value="<?php echo $row{'p_id'}?>"><?php echo $row{'p_id'}?></td>
<td><button onclick="<?php echo change($some_information_to_your_cell)?>">Update</button></td>
<td><input type="submit" name="delete" value="Delete"></td>
</tr>
</table>
</form>
And, please try to make a function dynamically each row, don't hardcode it like function change1(), function change2(), function change3(), etc
Hope this will help you out. :)

Getting Array Value from Checkbox in 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.

multiple update array query gone wrong :(

hey guys im having trouble with an array. all i need is for the query to update 2 columns on the table based on the records id
The table has a column called OffID and it looks for any record that has not yet been authorised. to mark it authorised the user will select a check box for either authorise or deny and then press the submit button. however at the moment i have 9 records which show in the table each with there own unique id but when submit is selected it will only update one. any help in showing where ive gone wrong would be grateful and cheers in advance :)
ok i edited the code but it is only now setting the first record. so if there are 8 records and i choose accept for the first record and deny for the second record both the accept and deny are set to the first record in the database my new code is below
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/Apollo/dbc.php";
include_once($path);
$rs_results = mysql_query("SELECT * FROM off WHERE IsItAuthorised='0' and isitsick='0' ORDER BY DayOff");
?>
<html>
<head>
<title>Administration Main Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php
if (isset($_POST['submit'])) {
//Assign each array to a variable
$id = $_POST['id'];
$approve = $_POST['approve'];
$deny = $_POST['deny'];
$limit = count($rs_results);
$values = array(); // initialize an empty array to hold the values
for($k=0;$k<$limit;$k++){
$msg[] = "$limit New KPI's Added";
$query = "UPDATE off SET Authorised = '$approve[$k]', Deny = '$deny[$k]' WHERE OffID = '$id[$k]'";
}
$Event = "INSERT INTO events (UserName, Event ) VALUES ('$_SESSION[user_name]', 'Entered New KPI' )";
echo $query;
if (!mysql_query($query,$link)){
die('Error: ' . mysql_error());
} else {
mysql_query($Event);
echo "<div class=\"msg\">" . $msg[0] . "</div>";
}
}
?>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="14%" valign="top"><?php
?>
</td>
<td width="74%" valign="top" style="padding: 10px;">
<p><?php
if(!empty($msg)) {
echo $msg[0];
}
?></p>
<p>
<?php
$cond = '';
$sql = "select * from off ";
$rs_total = mysql_query($sql) or die(mysql_error());
$total = mysql_num_rows($rs_total);
?>
<p>
<form name "searchform" action="/Apollo/Admin/HolidayRequests.php" method="post">
<table width="100%" border="0" align="center" cellpadding="2" cellspacing="0">
<tr class="mytables">
<td width="4%"><font color="white"><strong>ID</font></strong></td>
<td width="4%"> <font color="white"><strong>Staff Member</font></strong></td>
<td width="10%"><font color="white"><strong>Day Off</font></strong></div></td>
<td width="10%"><font color="white"><strong>Is It Authorized</font></strong></div></td>
<td width="15%"> </td>
</tr>
<tr>
<td> </td>
<td width="10%"> </td>
<td width="17%"><div align="center"></div></td>
<td> </td>
</tr>
<?php while ($rrows = mysql_fetch_array($rs_results)) {?>
<tr>
<td><input name="id[]" id="id[]" size="4" value="<?php echo $rrows['OffID'];?>" /></td>
<td><?php echo $rrows['StaffMember']; ?></td>
<td><?php echo date('d/m/Y', strtotime($rrows['DayOff']));?></div></td>
<td> <span id="approve<?php echo $rrows['id']; ?>">
<?php if(!$rrows['IsItAuthorised']) { echo "Pending"; } else {echo "Authorized"; }?>
</span> </td>
<td>
<input type="checkbox" name="approve[]" id="approve[]" value="1"> Approve
<input type="checkbox" name="deny[]" id="deny[]" value="1"> Deny
</td>
</tr>
<?php } ?>
</table>
<input name="submit" type="submit" id="submit" value="Submit">
</form>
</p>
<?php
?>
<p> </p>
<p> </p>
<p> </p>
<p> </p></td>
<td width="12%"> </td>
</tr>
</table>
</body>
</html>
isn't it because your $id etc isn't passes an array:
$id = $_POST['id'];
$approve = $_POST['approve'];
$deny = $_POST['deny'];
You're using $_POST['id'] but nowhere in your <form/> do I see any <input name="id[]"/> which could provide the data

Categories