Modify array data in a form within a foreach loop - php

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();

Related

how to get another value with ajax from foreach table

I have table from foreach, in this table i create submit with ajax (id="detail"), but why when i submit i just get first row, when i click second row value, i get first row value not second row value ?
<form action="<?php echo base_url() ?>index.php/stock_opname/proses_detail" method="post">
<table class="table table-striped">
<thead>
<tr>
<th>No</th>
<th>SO No</th>
<th>Opname Date</th>
<th>Warehouse</th>
<th>Type</th>
<th>Approve</th>
<th>Close period</th>
<th>Detail</th>
</tr>
</thead>
<tbody>
<?php $no=1; foreach ($show as $key) { ?>
<tr>
<td><?php echo $no ?></td>
<td><input type="text" id="sono" value="<?php echo $key->sono ?>"></td>
<td><input type="text" id="opnamedate" value="<?php echo $key->opnamedate ?>"></td>
<td><input type="text" id="warehousecode" value="<?php echo $key->warehousecode ?>"></td>
<td><input type="text" id="stocktypeid" value="<?php echo $key->stocktypeid ?>"></td>
<td></td>
<td></td>
<td>Detail</td>
</tr>
<?php $no++;} ?>
</tbody>
</table>
</form>
<script type="text/javascript">
//Ajax Load data from ajax
$(document).on('click', '#detail', function(){
var sono = $('#sono').val();
var opnamedate = $('#opnamedate').val();
var wh = $('#warehousecode').val();
var stocktypeid = $('#stocktypeid').val();
alert(sono);
});
you have to make the id also dynamic and also the script sholud be dynamic.Hope you get it
id="detail1"
.on('click', '#detail1', function() ----for first
.on('click', '#detail2', function() ----for second and so on
<form action="<?php echo base_url() ?>index.php/stock_opname/proses_detail" method="post">
<table class="table table-striped">
<thead>
<tr>
<th>No</th>
<th>SO No</th>
<th>Opname Date</th>
<th>Warehouse</th>
<th>Type</th>
<th>Approve</th>
<th>Close period</th>
<th>Detail</th>
</tr>
</thead>
<tbody>
<?php $no=1; foreach ($show as $key) { ?>
<tr>
<td><?php echo $no ?></td>
<td><input type="text" id="sono<?php echo $no; ?>" value="<?php echo $key->sono ?>"></td>
<td><input type="text" id="opnamedate<?php echo $no; ?>" value="<?php echo $key->opnamedate ?>"></td>
<td><input type="text" id="warehousecode<?php echo $no; ?>" value="<?php echo $key->warehousecode ?>"></td>
<td><input type="text" id="stocktypeid<?php echo $no; ?>" value="<?php echo $key->stocktypeid ?>"></td>
<td></td>
<td></td>
<td>Detail</td>
</tr>
<?php $no++;} ?>
</tbody>
</table>
</form>
<script type="text/javascript"> //Ajax Load data from ajax
function getDetails(no){
var sono = $('#sono'+no).val();
var opnamedate = $('#opnamedate'+no).val();
var wh = $('#warehousecode'+no).val();
var stocktypeid = $('#stocktypeid'+no).val();
alert(sono);}
hope this will help
Can you try this ?
$('#detail').click(function(){
var sono = $(this).siblings('#sono').val();
var opnamedate = $(this).siblings('#opnamedate ').val();
var wh = $(this).siblings('#wh').val();
var stocktypeid = $(this).siblings('#stocktypeid ').val();
alert(sono);
});

Better iteration to display Object properties PHP

I'm looking for a better way to iterate through an object and display its contents.
FormController:
public function run(){
$tabteachers='';
if(!empty($_SESSION['apply']) && !empty($_SESSION['application'])){
$tabteachers = DB::getInstance()->select_teacher_id($_SESSION['login']);
}
require_once(VIEW_PATH.'formdeux.php');
}
Db.class function():
public function select_teacher_id($login){
$query = 'SELECT * FROM teachers,internships,students WHERE teachers.email_teacher = internships.email_responsible_internship AND students.registry_number_student = internships.registry_student_internship AND internships.registry_student_internship = '. $this->_db->quote ( $login );
$result = $this->_db->query ( $query );
if ($result->rowcount () != 0) {
while ( $row = $result->fetch () ) {
$teacher[]= new teacher ( $row->email_teacher,$row->firstname_teacher,$row->lastname_teacher,$row->responsible_internship_teacher,NULL);
}
return $teacher;
}
}
Form View:
<table>
<thead>
<tr>
<th width="20%" class="decoration">contact</th>
</tr>
</thead>
<tbody>
<?php foreach ($tabteachers as $teacher) { ?>
<tr>
<td>Lastname: <td>
<input type="text" name="lastnamepro" value="<?php echo $teacher->lastname_teacher() ?>" size="100px">
</tr>
<tr>
<td>Firstname: <td>
<input type="text" name="firstnamepro" value="<?php echo $teacher->firstname_teacher() ?>" size="100px">
</tr>
<tr>
<td>Email address: <td>
<input type="text" name="emailpro" value="<?php echo $teacher->email_teacher() ?>" size="100px">
</tr>
<tr>
<td>Service: <td>
<input type="text" name="servicepro" value="null" size="100px">
</tr>
<tr>
<td>mobile number: <td>
<input type="text" name="phonenumberpro" value="aucun numero" size="100px">
</tr>
<?php } ?>
</tbody>
</table><br>
Db connection:
private static $instance = null;
private $_db;
private function __construct() {
try {
$this->_db = new PDO ('mysql:host=localhost;dbname=ProjectWeb;charset=utf8', 'root', '' );
$this->_db->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->_db->setAttribute ( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ );
} catch ( PDOException $e ) {
die ( 'Erreur de connexion à la base de donnée : ' . $e->getMessage () );
}
}
// Pattern Singleton
public static function getInstance() {
if (is_null ( self::$instance )) {
self::$instance = new Db ();
}
return self::$instance;
}
thanks for your help in advance!
I see you have set the default fetch mode to FETCH_OBJ , in this particular case though I think you can rather get the entire result set as an array using PDO's fetchAll method and then iterate though it,
public function select_teacher_id($login){
$query = 'SELECT * FROM teachers,internships,students WHERE
teachers.email_teacher = internships.email_responsible_internship
AND students.registry_number_student = internships.registry_student_internship
AND internships.registry_student_internship = '. $this->_db->quote ( $login );
$result = $this->_db->query ( $query );
if ($result->rowcount () != 0) {
//fetch the entire result set as a multi-dimensional assoc array
$teachers_result = $result->fetchAll(PDO::FETCH_ASSOC);
return $teachers_result;
}
}
// VIEW
<table>
<thead>
<tr>
<th width="20%" class="decoration">contact</th>
</tr>
</thead>
<tbody>
<?php foreach ($tabteachers as $teacher) { ?>
<tr>
<td>Lastname: <td>
<input type="text" name="lastnamepro" value="<?php echo $teacher['lastname_teacher'] ?>" size="100px">
</tr>
<tr>
<td>Firstname: <td>
<input type="text" name="firstnamepro" value="<?php echo $teacher['firstname_teacher'] ?>" size="100px">
</tr>
<tr>
<td>Email address: <td>
<input type="text" name="emailpro" value="<?php echo $teacher['email_teacher'] ?>" size="100px">
</tr>
<tr>
<td>Service: <td>
<input type="text" name="servicepro" value="null" size="100px">
</tr>
<tr>
<td>mobile number: <td>
<input type="text" name="phonenumberpro" value="aucun numero" size="100px">
</tr>
<?php } ?>
</tbody>
</table><br>

php foreach() displays error MVC architecture

I have a problem detecting the error which I'm receiving.
Warning: Invalid argument supplied for foreach()
I'm trying to display an object's entities which are stored using Phpmyadmin. I'm using an MVC architecture.
FormController:
public function run(){
$tabteachers='';
if(!empty($_SESSION['apply']) && !empty($_SESSION['application'])){
$tabteachers = DB::getInstance()->select_teacher_id($_SESSION['login']);
}
require_once(VIEW_PATH.'formdeux.php');
}
Db.class function():
public function select_teacher_id($login){
$query = 'SELECT * FROM teachers,internships,students WHERE teachers.email_teacher = internships.email_responsible_internship AND students.registry_number_student = internships.registry_student_internship AND internships.registry_student_internship = '. $this->_db->quote ( $login );
$result = $this->_db->query ( $query );
if ($result->rowcount () != 0) {
while ( $row = $result->fetch () ) {
$teacher[]= new teacher ( $row->email_teacher,$row->firstname_teacher,$row->lastname_teacher,$row->responsible_internship_teacher,NULL);
}
return $teacher;
}
}
Form View:
<table>
<thead>
<tr>
<th width="20%" class="decoration">contact</th>
</tr>
</thead>
<tbody>
<?php foreach ($tabteachers as $teacher) { ?>
<tr>
<td>Lastname: <td>
<input type="text" name="lastnamepro" value="<?php echo $teacher->lastname_teacher() ?>" size="100px">
</tr>
<tr>
<td>Firstname: <td>
<input type="text" name="firstnamepro" value="<?php echo $teacher->firstname_teacher() ?>" size="100px">
</tr>
<tr>
<td>Email address: <td>
<input type="text" name="emailpro" value="<?php echo $teacher->email_teacher() ?>" size="100px">
</tr>
<tr>
<td>Service: <td>
<input type="text" name="servicepro" value="null" size="100px">
</tr>
<tr>
<td>mobile number: <td>
<input type="text" name="phonenumberpro" value="aucun numero" size="100px">
</tr>
<?php } ?>
</tbody>
</table>
thanks for your help in advance!

Multiple insert array POST values from foreach loop into mysql

<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++;
}
?>

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