Multiple insert array POST values from foreach loop into mysql - php

<table class="table table-bordered">
<thead>
<tr>
<th class="col-md-2">First Name</th>
<th class="col-md-2">Last Name</th>
<th class="col-md-2">Present</th>
<th class="col-md-2">Absent</th>
</tr>
</thead>
<?php foreach($teacher_names as $name): ?>
<tbody>
<tr>
<td class="col-md-2"><input class="form-control" type="text" readonly="readonly" name="f_name" value="<?php echo $name['first_name']; ?>"></td>
<td class="col-md-2"><input class="form-control" type="text" readonly="readonly" name="l_name" value="<?php echo $name['last_name']; ?>"></td>
<td class="col-md-2"><input type="checkbox" name="present" value="Y"></td>
<td class="col-md-2"><input type="checkbox" name="absent" value="N"></td>
</tr>
</tbody>
<?php endforeach;?>
</table>
I want to be able to access all values in my database which at the moment is 10. I want to get all the $_POST values and then insert them into the database but it seems i only get the one POST value in the foreach loop which is the last key value. An example of the php script is
public function teachers_attendance($first_name, $last_name, $present, $absent){
$sql = "INSERT INTO teacher_attendance($first_name, $last_name, $present, $absent)
VALUES(:first_name, :last_name, :present, :absent)";
$stmt = $this->_connection->prepare($sql);
$stmt->bindValue(':first_name', $first_name, PDO::PARAM_INT);
$stmt->bindValue(':last_name', $last_name, PDO::PARAM_STR);
$stmt->bindValue(':present', $present, PDO::PARAM_STR);
$stmt->bindValue(':absent', $absent, PDO::PARAM_STR);
$stmt->Execute();
$num_rows = $stmt->rowCount();
if($num_rows > 0){
echo "Yes";
}else{
echo "No";
}
}
I just would want to be able to access all the POST value and checkbox values into an array and then insert them all in the database. I would be grateful if i can have some solutions to this problem.

Since it didn't click with me the first time about un-matching keys when checkboxes are not selected, I've written up another method of accomplishing what you're after.
So your template should be as follows:
<table class="table table-bordered">
<thead>
<tr>
<th class="col-md-2">First Name</th>
<th class="col-md-2">Last Name</th>
<th class="col-md-2">Present</th>
<th class="col-md-2">Absent</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach($teacher_names as $name):
?>
<tr>
<td class="col-md-2"><input class="form-control" type="text" readonly="readonly" name="f_name_<?php echo $i; ?>" value="<?php echo $name['first_name']; ?>" /></td>
<td class="col-md-2"><input class="form-control" type="text" readonly="readonly" name="l_name_<?php echo $i; ?>" value="<?php echo $name['last_name']; ?>" /></td>
<td class="col-md-2"><input type="checkbox" name="present_<?php echo $i; ?>" value="Y" /></td>
<td class="col-md-2"><input type="checkbox" name="absent_<?php echo $i; ?>" value="N" /></td>
</tr>
<?php
$i++;
endforeach;
?>
</tbody>
</table>
Then you start at 0, add 1 each time, and loop until numbered name fields are no longer found (at which point it is assumed there are no more entries)
<?php
// First row to check is 0, as per template
$i = 0;
// Loop while f_name_* and l_name_* are found (if not found, it is assumed there are no more rows)
while( isset( $_POST['f_name_'.$i] ) && isset( $_POST['l_name_'.$i] ) )
{
// Get and set name variables (based on current row)
$first_name = $_POST['f_name_'.$i];
$last_name = $_POST['l_name_'.$i];
// Presence and absence are checkboxes with a Y value, so we'll set these to 'N' if not found
$present = ( isset( $_POST['present_'.$i] ) ? $_POST['present_'.$i] : 'N' );
$absent = ( isset( $_POST['absent_'.$i] ) ? $_POST['absent_'.$i] : 'N' );
// Call the teachers_attendance function
teachers_attendance($first_name, $last_name, $present, $absent);
// Increment the row to check
$i++;
}
?>

Related

INSERT INTO multiple rows from a dynamic html table to MYsql using PHP

The Scenario
I have a scoring card that is populated from another table in the MTSQL with an unknown amount of players. each week the players needs to be scored and those scores needs to be input into the mySQL.
The dynamic html table create for the Mysql table call member.
<form method="post" action="scores-add" id="member-add-form" enctype="multipart/form-data">
<div class="table-responsive">
<table id="data-table-1" class="table table-striped table-bordered">
<thead>
<tr>
<th class="align-middle">Name</th>
<th class="align-middle">Team</th>
<th class="align-middle">Week</th>
<th class="align-middle">Score 1</th>
<th class="align-middle">Score 2</th>
<th class="align-middle">Score 3</th>
<th class="align-middle">Score 4</th>
<th class="align-middle">Score 5</th>
<th class="align-middle">Score 6</th>
<th class="align-middle">Score 7</th>
<th class="align-middle">Score 8</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM member ORDER BY member_name ASC";
$result = mysqli_query($db,$sql) or die("Database access failed: " . mysqli_error());
while ($team = mysqli_fetch_assoc($result)) {
?>
<tr >
<td class="align-middle"><input type="text" name="scoring_1" value="<?php echo $team["member_name"]; ?>" readonly hidden> <?php echo $team["member_name"]; ?></td>
<td class="align-middle"><input type="text" name="scoring_2" value="<?php echo $team["member_team"]; ?>" readonly hidden> <?php echo $team["member_team"]; ?></td>
<td class="align-middle"><input type="text" name="scoring_3" value="" readonly hidden> </td>
<td class="align-middle"><input type="checkbox" name="scoring_4" value="5"></td>
<td class="align-middle"><input type="checkbox" name="scoring_5" value="10"></td>
<td class="align-middle"><input type="checkbox" name="scoring_6" value="5"></td>
<td class="align-middle"><input type="checkbox" name="scoring_7" value="5"></td>
<td class="align-middle"><input type="checkbox" name="scoring_8" value="5"></td>
<td class="align-middle"><input type="checkbox" name="scoring_9" value="5"></td>
<td class="align-middle"><input type="checkbox" name="scoring_10" value="20"></td>
<td class="align-middle"><input type="checkbox" name="scoring_11" value="50"></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<div class="form-row mb-3">
<button type="submit" class="btn btn-primary btn-block" name="score_add_btn">Add Score</button>
</div>
</form>
The function to add the table to the SQL
/ call the team_edit() function if team_edit_btn is clicked
if (isset($_POST['score_add_btn'])) {
score_add();
}
// LOGIN USER
function score_add(){
global $db, $errors, $member_id, $member_name_edit, $member_team_edit, $members_view_url;
// grap form values
$scoring_1 = $_POST['scoring_1'];
$scoring_2 = $_POST['scoring_2'];
$scoring_3 = $_POST['scoring_3'];
$scoring_4 = $_POST['scoring_4'];
$scoring_5 = $_POST['scoring_5'];
$scoring_6 = $_POST['scoring_6'];
$scoring_7 = $_POST['scoring_7'];
$scoring_8 = $_POST['scoring_8'];
$scoring_9 = $_POST['scoring_9'];
$scoring_10 = $_POST['scoring_10'];
$scoring_11 = $_POST['scoring_11'];
// make sure form is filled properly
if (empty($scoring_1)) {
array_push($errors, "Name is required");
}
if (count($errors) == 0) {
$query = "INSERT INTO scoring (scoring_1, scoring_2, scoring_3, scoring_4, scoring_5, scoring_6, scoring_7, scoring_8, scoring_9, scoring_10, scoring_11 )
VALUES ('$scoring_1', '$scoring_2', '$scoring_3', '$scoring_4', '$scoring_5', '$scoring_6', '$scoring_7', '$scoring_8', '$scoring_9', '$scoring_10', '$scoring_11')";
mysqli_query($db, $query);
$_SESSION['success'] = "<h4>Done</h4>";
header("location: $leaderboard_menmber_url");
}else {
$_SESSION['failure'] = "Error updating record: " . $db->error;
header("location: $leaderboard_menmber_url");
}
$db->close();
}
The Problem
The function only adds the last line from the dynamic html table to the database.
The desired outcome.
Each entry in the dynamic HTML table needs to be added to the MySQL as its own entry.
<input type="text" name="scoring_1" value="<?php echo $team["member_name"]; ?>
here you set your variable name to scoring_1 but the next row of table will override that (Instead the browser may send the data, but php will create a variable scoring_1 and assign one of the given values to them. To solve this problem set the name to scoring_1[]
<input type="text" name="scoring_1[]" value="<?php echo $team["member_name"]; ?>
This say php to make an array and store the values there. Futher you can inprove your code when you use something like the team id as row index and used a fixed number as column in a 2 dimensional array
<input type="text" name="scoring[<?php echo $team["id"];>][1]" value="<?php echo $team["member_name"]; ?>

Modify array data in a form within a foreach loop

There have a form in a view page that take data as a multidimensional array.In edit mode that form value is fetching and showing data through a foreach loop.
Now my problem is i'm unable to modify that form data in that foreach loop and send it to database. I gone through some posts about foreach key concept but how do I take modified value here in html and send it to database within this foreach loop?
My code fetching data properly but fail to update data.
Here is my code of view page :
<table class="table table-striped" id="dataTable">
<thead>
<tr>
<th>Subscription</th>
<th>Description</th>
<th>Interval</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
if (!empty($invoice_detail)) {
foreach ($invoice_detail as $key => $result) { ?>
<tr>
<td><input type="text" name="invoice[$key][invoice_detail_subs]" id="invoice_detail_subs"
value="<?php echo $result->invoice_detail_subs; ?>"/></td>
<td><input type="text" name="invoice[$key][invoice_detail_desc]" id="invoice_detail_desc"
value="<?php echo $result->invoice_detail_desc; ?>"/></td>
<td><input type="text" name="invoice[$key][invoice_detail_interval]" id="invoice_detail_interval"
value="<?php echo $result->invoice_detail_interval; ?>"/></td>
<td><input type="text" name="invoice[$key][invoice_detail_amount]" id="invoice_detail_amount"
value="<?php echo $result->invoice_detail_amount; ?>"/></td>
<td></td>
</tr>
<?php }
} ?>
</tbody>
</table>
Here it is Update code in in controller :
if ($this->input->post('Submit')) {
$query = $this->db->query(
"SELECT * FROM ".$this->db->dbprefix."invoice_details WHERE invoice_detail_invoie_id ='".$id."' "
);
$fetch = $query->row();
$rows = $query->num_rows();
if ($id) {
$data1 = [
'invoice_detail_subs' => $this->input->post('invoice_detail_subs'),
'invoice_detail_desc' => $this->input->post('invoice_detail_desc'),
'invoice_detail_interval' => $this->input->post('invoice_detail_interval'),
'invoice_detail_amount' => $this->input->post('invoice_detail_amount'),
'invoice_detail_mddt' => date("Y-m-d H:i:s")
];
$this->db->update('invoice_details', $data1, 'invoice_detail_invoie_id = '.$id);
}
}
View Code
<table class="table table-striped" id="dataTable">
<thead>
<tr>
<th>Subscription</th>
<th>Description</th>
<th>Interval</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
if (is_object($invoice_detail)) :
foreach ($invoice_detail as $key => $result) : ?>
<tr>
<td><input type="text" name="invoice_detail_subs"
value="<?= $result->invoice_detail_subs; ?>"/></td>
<td><input type="text" name="invoice_detail_desc"
value="<?= $result->invoice_detail_desc; ?>"/></td>
<td><input type="text" name="invoice_detail_interval"
value="<?= $result->invoice_detail_interval; ?>"/></td>
<td><input type="text" name="invoice_detail_amount"
value="<?= $result->invoice_detail_amount; ?>"/></td>
<td></td>
</tr>
<?php endforeach;
endif; ?>
</tbody>
update code in controller
if ($this->input->method()=="post") {
if ($id) {
$data1 = ['invoice_detail_subs'=> $this->input->post('invoice_detail_subs'),
'invoice_detail_desc' => $this->input->post('invoice_detail_desc'),
'invoice_detail_interval' => $this->input->post('invoice_detail_interval'),
'invoice_detail_amount' => $this->input->post('invoice_detail_amount'),
'invoice_detail_mddt' => date("Y-m-d H:i:s")];
$this->db->update($this->db->dbprefix."invoice_details", $data1,['invoice_detail_invoie_id'=>$id]);
}
}
$query = $this->db->select('*')->where(["invoice_detail_invoie_id"=>$id])->get($this->db->dbprefix."invoice_details");
$fetch = $query->row();
$rows = $query->num_rows();

Insert data from while loop into a table with php

I'm creating a form using HTML and PHP. I have created a form which I want to submit and save that data in database.
I'm trying to submit a form with data that comes from a while loop. All input values are getting generated by while loop.
The code looks like this.
<table width="1348" border="0" class="table table-striped" >
<tr>
<td width="106"> </td>
<td width="332"><strong>Product Code</strong></td>
<td width="375"><strong>Product Name</strong></td>
<td width="211"><strong>QTY</strong></td>
</tr>
<?php
$i = 0;
$rowset = mysql_query("select * from product_detail where productID='".$data['productCode']."'");
while($stuff = mysql_fetch_array($rowset)){
?>
<tr>
<td><input type="text" name="code[<?php echo $i?>]" value="<?php enter code hereecho $stuff['code'];?>"/></td>
<td><input type="text" name="name[<?php echo $i?>]" value="<?php echo $stuff['name'];?>" size="50"/></td>
<td><input type="text" name="qty[<?php echo $i?>]" value="<?php echo $stuff['qty'];?>" size="10"/></td>
</tr>
<?php $i++; }?>
<tr id="last">
</table>
<input type="submit" name="save id="save" class="btn btn-primary btn-lg"/>
This is the code to add the data to database.
$code=$_POST['code'.$i];
$name=$_POST['name'.$i];
$qty=$_POST['qty'.$i];
$query = mysqli_query($con,"insert into stock(productCode, productName, qty) values ('".$code."', '".$name."','".$qty."')") or die(mysqli_error($con));
First, use prepared statement with bind_param as your script is totally exposed to sql injection.
Second, you can add input type hidden for the number of rows
<form action="" method="POST">
<table width="1348" border="0" class="table table-striped" >
<tr>
<td width="106"> </td>
<td width="332"><strong>Product Code</strong></td>
<td width="375"><strong>Product Name</strong></td>
<td width="211"><strong>QTY</strong></td>
</tr>
<?php
$data['productCode'] = "1"; // sample data
$stmt = $con->prepare("SELECT * FROM product_detail WHERE productID = ?");
$stmt->bind_param("i", $data['productCode']);
$stmt->execute();
$result = $stmt->get_result();
$i = 0;
while($stuff = $result->fetch_assoc()) {
?>
<tr>
<td></td>
<td><input type="text" name="code[<?php echo $i; ?>]" value="<?php echo $stuff['code'];?>"/></td>
<td><input type="text" name="name[<?php echo $i; ?>]" value="<?php echo $stuff['name']; ?>" size="50" /></td>
<td><input type="text" name="qty[<?php echo $i; ?>]" value="<?php echo $stuff['qty']; ?>" size="10" /></td>
</tr>
<?php
$i++;
}
?>
<input type="hidden" name="count" value="<?php echo $i; ?>" />
<tr id="last">
</table>
<input type="submit" name="save" id="save" class="btn btn-primary btn-lg"/>
</form>
post count with the form
<?php
if (isset($_POST['save'])) {
$count = $_POST['count'];
for ($i = 0; $i < $count; $i++) {
$code = $_POST['code'][$i]; // check empty and check if interger
$name = $_POST['name'][$i]; // check empty and strip tags
$qty = $_POST['qty'][$i]; // check empty and check if interger
$stmt = $con->prepare("INSERT INTO stock (productCode, productName, qty) VALUES (?, ?, ?)");
$stmt->bind_param("iss",$code,$name,$qty);
$stmt->execute();
}
}
?>
You may also want to check if post values are empty with other necessary validation before insert
Since the table is dynamically filled, you need to use an array as the name attribute
<table>
<tr>
<th>Name</th>
<th>Present</th>
<th>Excused</th>
<th>Unexcused</th>
<th>Ext</th>
</tr>
<?php
$query = "select * from TbCard";
$sql = mysqli_query($connect, $query);
$count = 0;
while ($data = mysqli_fetch_array($sql)) {
?>
<tr>
<td>
<input name="tableRow[<?php echo $count; ?>]['dataName']" id='name' type='text' value="<?php echo $data['Name'];?>" readonly style='border:none;width:350px'></input>
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Present"> Present
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Excused"> Excused
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Unexcused"> Unexcused
</td>
</tr>;
<?php
$count++;
}
?>
</table>
The php would be something like this, assuming that the data has values in it:
$tableRow = $_POST['tableRow'];
foreach($tableRow as $row){
/* here insert data from post */
echo $row['dataName'].' '.$row['status'].'<br/>';
}
To see the content of the array, use print_r($tableRow)
in this case i use a name tableRow

Pass back values to form to populate it? (lots of values)

I need to pass back a large string of results to a form, so that the form can read those results from the URL and then populate the form with them. Problem is, the link ends up being:
&key=value&key=value ... until it can't process anymore (I assume a URL has a length limit?) resulting in my form not being able to fully populate. I need another way to pass values back to my form file.
VIEW.php file (basically just a table of values right as they are from the database, with the first column "id" being a link. When I click on "id", it goes back to my add.php(form page) and populates the form with the data matching that id)
<table border="0" cellpadding="0" cellspacing="0" id="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>MANUFACTURER</th>
<th>MODEL</th>
<th>DESCRIPTION</th>
<th>ON HAND</th>
<th>REORDER</th>
<th>COST</th>
<th>PRICE</th>
<th>SALE</th>
<th>DISCOUNT</th>
<th>DELETED</th>
<th></th>
</tr>
</thead>
<tbody>
<?php } ?>
<?php
// loop to fetch data
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='molszewski1_a2_add.php'>$row[id]</a></td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td>$row[deleted]</td>";
$status = "$row[deleted]";
echo "<td><a href='molszewski1_a2_delete.php?id=$row[id]&flag=$status&sort=$sort'>";
$status = "$row[deleted]";
if ($status == 'n') {
$flag = "restore";
echo "delete";
} else if ( $status == 'y') {
$flag = "delete";
echo "restore";
}
echo "</a></td>";
echo "</tr>";
} ?>
<?php { ?>
</tbody>
</table>
ADD.php (form page where the form is supposed to fetch the data and populate it)
<?php
// If no form has been submitted, present form
if (empty($_GET))
{
add_form();
}
// if a form has been submitted
else
{
// if form_validity() == 1, proceed to connect
if (form_validity() == 1)
{
// connect to mysql + database
connect();
$saleItem = "n";
$discountItem = "n";
if( array_key_exists( 'saleItem', $_GET ) && $_GET['saleItem'] == 'y' )
{ $saleItem = "y"; }
if( array_key_exists( 'discountItem', $_GET ) && $_GET['discountItem'] == 'y' )
{ $discountItem = "y"; }
// get values from form, insert into database
$sql=("INSERT INTO inventory (name,
manufac,
model,
descrip,
onhand,
reorder,
cost,
price,
sale,
discont,
deleted)
VALUES ('$_GET[itemName]',
'$_GET[manufacturer]',
'$_GET[model]',
'$_GET[description]',
'$_GET[numberOnHand]',
'$_GET[reorderLevel]',
'$_GET[cost]',
'$_GET[sellingPrice]',
'$saleItem',
'$discountItem', 'n')");
// if the query doesn't work, display error message
if (!(mysql_query($sql))) { die ("could not query: " . mysql_error()); }
add_form();
// redirect to view.php after form submission
// use php instead
echo "<meta http-equiv='REFRESH' content='0;url=molszewski1_a2_view.php'>";
}
else
{
// if form is not valid (form_validity returns 0), display error messages
add_form();
}
}
?>
FUNCTIONS.php (all my functions for stuff like the form)
<?php function page_navigation(){ ?>
<div class="center">
<input type="button" value="ADD" />
<input type="button" value="VIEW" />
<input type="button" value="VIEW DELETED" />
<input type="button" value="VIEW ACTIVE" />
<br />
<br />
</div>
<?php } ?>
<?php function add_form() { ?>
<form action="molszewski1_a2_add.php" method="get" id="form">
<table width="529px">
<tr>
<td>ITEM NAME</td>
<td><input name="itemName" size="30" type="text" value="<?php echo $_GET["itemName"] ?>"/></td>
</tr>
<tr>
<td>MANUFACTURER</td>
<td><input name="manufacturer" size="30" type="text" value="<?php echo $_GET["manufacturer"] ?>"/></td>
</tr>
<tr>
<td>MODEL</td>
<td><input name="model" size="30" type="text" value="<?php echo $_GET["model"] ?>"/></td>
</tr>
<tr>
<td>DESCRIPTION</td>
<td><textarea name="description" rows="3" cols="20"><?php echo $_GET["description"] ?></textarea></td>
</tr>
<tr>
<td>ON HAND</td>
<td><input name="numberOnHand" size="30" type="text" value="<?php echo $_GET["numberOnHand"] ?>"/></td>
</tr>
<tr>
<td>REORDER LEVEL</td>
<td><input name="reorderLevel" size="30" type="text" value="<?php echo $_GET["reorderLevel"] ?>"/></td>
</tr>
<tr>
<td>COST</td>
<td><input name="cost" size="30" type="text" value="<?php echo $_GET["cost"] ?>"/></td>
</tr>
<tr>
<td>SELLING PRICE</td>
<td><input name="sellingPrice" size="30" type="text" value="<?php echo $_GET["sellingPrice"] ?>"/></td>
</tr>
<tr>
<td>SALE ITEM</td>
<td>
<input type="checkbox" name="saleItem" value="y" <?php if( isset( $_GET['saleItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td>DISCOUNTED ITEM</td>
<td>
<input type="checkbox" name="discountItem" value="y" <?php if( isset( $_GET['discountItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="save" name="submit" id="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Use method="post" and $_POST (instead of $_GET).
POST requests can be much larger than GET requests as GET requests are limited by the maximum length of a URL. POST requests are limited by the size of the max_post_size ini-value which is usually a few megabytes.

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