How to get several data from a form? - php

I have two added form. In the first, I choose one client and for him I add several domains names.
Then, when I clik to next, I arrived on a second form in which there are the several domains names (I added before ) in each row with others fields for each one (registar, url and remark). It seems to like this :
toto.com | Directnic | www.toto.com | blablabla
toto.fr | Afnic | www.toto.fr | bla
toto.net | Gandi | www.toto.net | blabla
But when I want to recover this data into my action to add them into my database, I get only the last line. Why ?
My form :
<form action="<?php echo url_for('#add_domaines');?>" method="post">
<?php echo $form->renderGlobalErrors() ?>
<table class="form_add_domaines">
<thead>
<tr>
<th><?php echo $form['nom_domaine']->renderLabel()?></th>
<th><?php echo $form['compte_registar_id']->renderLabel() ?></th>
<th><?php echo $form['url']->renderLabel() ?></th>
<th><?php echo $form['remarque']->renderLabel() ?></th>
</tr>
</thead>
<tbody>
<?php
$domaines = explode("\n",$add_domaines);
for($i=0; $i<count($domaines); $i++)
{?>
<tr>
<td>
<?php
if(1==strcmp(' ', $domaines[$i]))
{
echo "<span style='color:red;'>"."<b>Warning, missing domain name.</b>"."</span>";
}
else
{
echo $domaines[$i];
}
?>
</td>
<td>
<?php echo $form['compte_registar_id']->renderError() ?>
<?php echo $form['compte_registar_id'] ?>
</td>
<td>
<?php echo $form['url']->renderError() ?>
<?php echo $form['url'] ?>
</td>
<td>
<?php echo $form['remarque']->renderError() ?>
<?php echo $form['remarque'] ?>
</td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
<tr>
<td>
<?php echo link_to(__('Back', array(), 'sf_admin'), '#domaine_new') ?>
</td>
<td>
<?php echo $form->renderHiddenFields(false) ?>
<input type="submit" class="submit" value="Add" />
</td>
</tr>
</tfoot>
</table>
</form>
My action :
[...]
$this->form = new AddDomainesForm();
$this->form->setDefault('client_id', $idClient);
$this->form->setDefault('nom_domaine', $noms_domaine);
if($request->isMethod('post'))
{
$name = $this->form->getName();
$values = $request->getParameter($name);
$files = $request->getFiles($name);
$this->form->bind($values, $files);
if($this->form->isValid())
{
print_r($values);break;
//$this->form->save();
$this->getUser()->setFlash('notice', 'OK.');
$this->redirect('#domaine');
}
}
print_r($values) return only the last row of my form
Array ( [compte_registar_id] => 1 [url] => www.toto.net [remarque] => blabla [nom_domaine] => toto.com toto.fr toto.net [client_id] => 17 [_csrf_token] => ... )
Thank you !

When multiple form elements have the same name, only the last one will be taken.
Did you see that cou can send arrays directly?
<inut type="text" name="foobarlist[]">
<inut type="text" name="foobarlist[]">
<inut type="text" name="foobarlist[]">
$_GET['foobarlist'] will return an array with 3 elements.
The brackets are the key.

Related

Hide first <td> if second in <td> is not selected any value (empty)

I need hide first one < td > <?php echo $user_feature['tab_title_single']; ?> if second < td > are abolutely empty without any checked ('tab_title_labels') values.
<?php
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
if (!empty($id)) {
$post_id = $id;
}
$user_features = array(
array(
'tab_title_single' => 'Apsauga',
'tab_title_labels' => 'Imobilaizeris,Signalizacija,Palydovinė sekimo sistema,Šarvuotas (apsaugos)'
),
array(
'tab_title_single' => 'Audio/video įranga',
'tab_title_labels' => 'CD grotuvas,MP3 grotuvas,Papildoma audio įranga,CD keitiklis,AUX jungtis,Žemų dažnių garsiakalbis,DVD grotuvas,USB jungtis,Laisvų rankų įranga,Apple CarPlay / Android Auto'
),
array(
'tab_title_single' => 'Eksterjeras',
'tab_title_labels' => 'Lengvojo lydinio ratlankiai,LED dienos žibintai,LED žibintai,Žibintai „Xenon“,Rūko žibintai,Kablys,Priekinių žibintų plovimo įtaisas,Stogo bagažinės laikikliai,Automatiškai užsilenkiantys veidrodėliai,Žieminių padangų komplektas'
),
array(
'tab_title_single' => 'Elektronika',
'tab_title_labels' => 'El. valdomi veidrodėliai,El. valdomas bagažinės dangtis,Automatiškai įsijungiantys žibintai,Borto kompiuteris,El. reguliuojama vairo padėtis,Kritulių jutiklis,Šildomi veidrodėliai,Atstumo jutiklių sistema,Beraktė sistema,Autopilotas,El. šildomas priekinis stiklas,Start-Stop funkcija,Valdymas balsu,Pavarų perjungimas prie vairo,LCD ekranas,Navigacija/GPS'
)
);
?>
<?php if (!empty($user_features)) {
if (!empty($post_id)) {
$features_car = get_post_meta($post_id, 'additional_features', true);
$features_car = explode(',', $features_car);
} else {
$features_car = array();
}
foreach ($user_features as $user_feature) { ?>
<table style="width: 100%; margin-bottom: 0px">
<tr>
<td style="width: 16%; padding-left:5px;">
<div class="heading-font" style="color:#555555;font-size: 13px;font-weight: 500;"><?php echo $user_feature['tab_title_single']; ?></div>
</td>
<td style="width: 84%; padding-left:5px;">
<?php $features = explode(',', $user_feature['tab_title_labels']); ?>
<?php if (!empty($features)): ?>
<?php foreach ($features as $feature): ?>
<?php
$checked = '';
$hide = 'style="display:none;"';
if (in_array($feature, $features_car)) {
$checked = 'checked';
$hide = '';
};
?>
<label <?php echo $hide; ?>>
<span class="featuresspan"><?php echo esc_attr($feature); ?></span>
</label>
<?php endforeach; ?>
<?php endif; ?>
</td>
</tr>
</table>
<?php }
}
?>
To compare two arrays ($features and $features_car) in php, the most direct tool for that task is array_intersect(). Although I should tell you (and researchers) that it would be far, far better to Normalize your table data so that you are not storing comma-separated values. Having a normalized/granular table of labels and their individual features spread across multiple rows will allow your application to enjoy cleaner and more efficient queries and allow you to move the filtering processes from php to mysql where it belongs.
Code: (Demo)
$features_car = ['USB jungtis', 'Rūko žibintai'];
foreach ($user_features as $user_feature) {
$features = explode(',', $user_feature['tab_title_labels']);
$matched_features = array_intersect($features, $features_car);
if ($matched_features) {
echo "<table>";
echo "<tr>";
echo "<td>";
echo "<div class=\"heading-font\">{$user_feature['tab_title_single']}</div>";
echo "</td>";
echo "<td>";
foreach ($matched_features as $show_feature) {
echo "<label><span class=\"featuresspan\">{$show_feature}</span></label>";
}
echo "</td>";
echo "</tr>";
echo "</table>";
}
}
Output:
<table>
<tr>
<td>
<div class="heading-font">Audio/video įranga</div>
</td>
<td>
<label><span class="featuresspan">USB jungtis</span></label>
</td>
</tr>
</table>
<table>
<tr>
<td>
<div class="heading-font">Eksterjeras</div>
</td>
<td>
<label><span class="featuresspan">Rūko žibintai</span></label>
</td>
</tr>
</table>
p.s. I don't know if I support the stacking of <table> elements like this, but it is up to you how you wish to style your markup. You should move ALL of your inline styles to an external stylesheet so that your markup is easier to read and manage. I removed the esc_attr() only so that my demo would work without errors -- you can safely apply it to all variables that you are concerned about.

How to insert looping radio button value into db

I'm really newbie at a code and these things, I try to make absent from, but I don't know how to take value from looping radio button, I don't know how to write it in the controller
this is my view
<tr>
<th>No</th>
<th>Nim</th>
<th>Nama Mahasiswa</th>
<th>Absen</th>
</tr>
</thead>
<tbody>
<?php $i=1; foreach ($absensi1 as $data) { ?>
<tr>
<th><?php echo $i; ?></th>
<th><?php echo $data->nim; ?></th>
<th><?php echo $data->nama; ?></th>
<th>
<label>
<input type="radio" name="kehadiran<?= $i ?>" <?php echo($data->absen == 'Hadir')?'checked':'' ?> value="1" >Hadir
<input type="radio" name="kehadiran<?= $i ?>" <?php echo($data->absen == 'Tidak Hadir')?'checked':'' ?> value="2" >
Tidak Hadir
<input type="radio" name="kehadiran<?= $i ?>" <?php echo($data->absen == 'Izin')?'checked':'' ?> value="3" >
Izin
</label>
</th>
</tr>
<?php $i++; } ?>
</tbody>
</table>
</div>
<a href="<?php echo base_url('absen/simpan') ?>" class="btn btn-primary pull-right" >Simpan</a>
</div>
and this is my controller, and it doesn't work actually, so how to write the controller for when I clicked simpan button it will be saved into my db
public function simpan()
{
$role = $this->session->userdata('role_id');
$absen = $this->input->post('kehadiran');
$nim = $this->input->post('nim');
$data =
[
'absen' =>$absen,
// 'setuju' => '1'
];
$this->db->set('mahasiswa',$data);
$this->db->update('mahasiswa');
redirect('Absen');
}
Why you are using different names ?
$_POST['Name_Of_Radio_Buttons'] gives value of radio button selected
You can Insert the value to db or If you want to change content make simple if statement
if($_POST['Name_Of_Radio_Buttons'] == 1 ){
$ToUpload = 'TestOne';
}else if($_POST['Name_Of_Radio_Buttons'] == 2){
$ToUpload = 'TestTwo';
}
and Upload $ToUpload to Db

Codeigniter explode to html table

I'm currently having issue explode to html table.
My Controller
public function idp_test()
{
$this->load->model('groups/groups_model');
$scholar_id = $this->session->userdata('scholar_id');
$groups = $this->groups_model->retrieve_groups_idp($this->scholar->level_id);
$content = array(
'groups' => $groups,
'scholar' => $this->scholar,
'page_title' => 'My individual development plan',
'page_view' => 'scholar/activities/idp_test',
'page_scripts_view' => 'scholar/inc/_choose_activities_scripts',
'sidebar_menu' => 'idp test'
);
$this->load->view("theme/base", $content);
}
My Model
public function retrieve_groups_idp($level_id)
{
$this->db->select("groups.*, levels.name as levelname");
$this->db->join('activities', 'groups.activity_ids = activities.activity_id' );
$this->db->join('levels', 'levels.level_id = groups.level_id', 'left' );
$this->db->join('activity_types', 'activities.activity_type_id = activity_types.activity_type_id', 'left' );
$this->db->where('groups.level_id', $level_id);
$this->db->group_by('groups_name');
$this->db->order_by('groups_name');
$qr = $this->db->get('groups');
return $qr->result();
}
public function retrieve_activity_desc($activity_ids)
{
$activity_desc_arr[] = explode(', ', $activity_ids);
foreach ($activity_desc_arr as $activity_id){
$this->db->select("activity_id as activityid, CONCAT(activities.name, ' - ', activity_types.name) AS description", FALSE);
$this->db->join('activity_types', 'activities.activity_type_id = activity_types.activity_type_id');
$this->db->where_in('activities.activity_id', $activity_id);
$qr = $this->db->get('activities');
return $qr->result();
}
}
My View
<?php foreach ($groups as $groups): ?>
<table class="table table-vcenter">
<thead>
<tr class="active">
<th><?php echo $groups->groups_name?></th> <!--Series Header -->
<th class="text-center"><small><strong>Module Type</strong></small></th>
<th class="text-center"><small><strong>Status</strong></small></th>
<th class="text-center"><small><strong>Action</strong></small></th>
</tr>
</thead>
<tbody>
<tr>
<td><?php
$rows = $this->groups_model->retrieve_activity_desc($groups->activity_ids);
foreach ($rows as $row){
echo var_dump($row->description);
}
?></td>
<td class="text-center">belom lagi</td>
<td class="text-center">TO ATTEND</td>
<td class="text-center">View Session</td>
</tr>
</tbody>
</table>
<?php endforeach ?>
i can't post images, so below are some sample in view so far
SERIES 1 FOR FS | MODULE TYPES | STATUS | ACTION
Series 1 - FILSeries 1 - CBLSeries 1 - PEL | belom lagi | to attend |
and what i need to achieve is like below sample in view
SERIES 1 FOR FS | MODULE TYPES | STATUS | ACTION
Series 1 - FIL | belom lagi | to attend |
Series 1 - CBL | belom lagi | to attend |
Series 1 - PEL | belom lagi | to attend |
I'm newbie with php & codeigniter, sorry with my english.
Thanks
Think about what you have in your view code:
<tr>
<td><?php
foreach($rows as $row){
var_dump($row->description);
}
?>
</td>
<td>belom lagi</td>
<td>to attend</td>
</tr>
Of course this will all be printed into one table cell, how it could produce anything else, right?
What you need is something like this:
<?php
foreach($rows as $row){
echo "<tr>"; // you need a new row for every entry
echo "<td>".$row->description."</td>";
echo "<td>belom lagi</td>";
echo "<td>to attend</td>";
echo "</tr>";
}
?>
After a few studies, i figured it out, just want to share with everybody.
EDITED - Controller
public function idp_test()
{
$this->load->model('groups/groups_model');
$this->load->model('activities/activity_type_model');
$scholar_id = $this->session->userdata('scholar_id');
$groups = $this->groups_model->retrieve_groups_idp($this->scholar->level_id);
foreach ($groups as $group) {
$act_desc = $this->groups_model->retrieve_activity_desc($group->activity_ids);
$group->activity_ids = $act_desc;
}
EDITED - View
<!-- START TABLE HEADER -->
<?php foreach ($groups as $group): ?>
<table class="table table-vcenter">
<thead>
<tr class="active">
<th><?php echo $group->groups_name?></th> <!--Series Header -->
<th class="text-center"><small><strong>Module Type</strong></small></th>
<th class="text-center"><small><strong>Status</strong></small></th>
<th class="text-center"><small><strong>Action</strong></small></th>
</tr>
</thead>
<tbody>
<?php foreach ($group->activity_ids as $session): ?>
<tr>
<td><?php echo $session->description; ?></td>
<td class="text-center"><?php echo $session->modulename; ?></td>
<td class="text-center">STATUS</td>
<td class="text-center">View Session</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endforeach ?>
<!-- END 1 -->
Come out as what i need.
Thank you stackoverflow.

codeigniter undefined offset error

I'm currently learning cart system with CI and got some problems
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 2
Filename: models/main_model.php
Line Number: 241
here's the code:
Controller:
function update_cart(){
$this->main_model->validate_update_cart();
redirect('cart');
}
Model:
function validate_update_cart(){
// Get the total number of items in cart
$total = $this->cart->total_items();
// Retrieve the posted information
$item = $this->input->post('rowid');
$qty = $this->input->post('qty');
// Cycle true all items and update them
for($i=0;$i < $total;$i++)
{
// Create an array with the products rowid's and quantities.
$data = array(
'rowid' => $item[$i], //this is line 241
'qty' => $qty[$i]
);
// Update the cart with the new information
$this->cart->update($data);
}
}
view:
<div id="main">
<?php if(!$this->cart->contents()):
echo 'You don\'t have any items yet.';
else:
?>
<?php echo form_open('cart/update_cart'); ?>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<td style="background-color:yellow;">Qty</td>
<td style="background-color:yellow;">Item No/td>
<td style="background-color:yellow;">Description</td>
<td style="background-color:yellow;">Color</td>
<td style="background-color:yellow;">Price</td>
<td style="background-color:yellow;">Sub-Total</td>
<td style="background-color:yellow;">Delete</td>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
<?php foreach($this->cart->contents() as $items): ?>
<?php echo form_hidden('rowid[]', $items['rowid']); ?>
<tr <?php if($i&1){ echo 'class="alt"'; }?>>
<td>
<?php echo form_input(array('name' => 'qty[]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?>
</td>
<td><a style="font-size:11px;"><?php echo $items['id']?></a></td>
<td><a style="font-size:11px;"><?php echo $items['name']; ?></a></td>
<td><a style="font-size:11px;"><?php echo $items['warna']?></a></td>
<td><a style="font-size:11px;">Rp. <?php echo number_format($items['price'],0,",",".");?></a></td>
<td><a style="font-size:11px;">Rp. <?php echo number_format($items['subtotal'],0,",",".");?></a></td>
<td><img src="<?= base_url();?>assets/image/hapus.png"></img></td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
<tr>
<td colspan="5"><strong>Total</strong></td>
<td colspan="2"><a align="right"><?php echo $this->cart->format_number($this->cart->total()); ?></a></td>
</tr>
</tbody>
</table>
<p><?php echo "<input type='submit' class='Button' value='Update'>";?></p>
<?php
echo form_close();
endif;
?>
edited the view, complete code.
when i click the update button it returned error live above.
thanks.
It seems that $this->cart->total_items() returns something different from the total items in the $item and $qty arrays. Later on, you are using this result to iterate these arrays, and the loop variable ($i) exceeds the arrays' boundaries.
Change your loop to:
for($i=0;$i < count($item);$i++)
You can choose count($qty) if you prefer, provided that the two arrays contain the same number of elements (which has to be true anyway, in order for the whole algorithm to work).
when you receive the post you should use
rowid[] instead of rowid

Display only specific array elements in a foreach loop

I have a page that contains an ordering form, on this form it lists the vendor information and then each of the products for the vendor underneath and in front of the product is an input field that allows the user to input the quantity of each product that they want.
Upon submitting the information goes to a confirmation page where I need to be able to show the order information. On the form on the order page, I have a hidden field that contains the vendor id. and the vendor id is put once for each vendor. What I need to be able to do is not only echo out the quantity but also echo out the vendor id specific for each order. My code is below. The first block is the order page and then the block below that will be the confirm page.
As it stands right now underneath every quantity it displays all the vendor ids as opposed to just the one I need.
<?php defined('C5_EXECUTE') or die("Access Denied.");?>
<div class="ccm-ui">
<?php
$db= Loader::db(); //This loads the database helper.
Loader::model('user'); //This loads the user Model.
$user = new User();
$userInfo = UserInfo::getByID($user->getUserID()); //This gets the user info for the current user.
$userCostCenter = $userInfo->getAttribute('cost_center'); //This sets a variable equal to the attribute Cost Center for the current user.
//The if statement below checks if the user is an admin and then displays the info accordingly.
if ($userCostCenter === "Admin") {
?>
<form name="SelectCostCenter" action="/adminorder" method="POST">
<select name="CostCenter">
<option value="unitedilluminating">United Illumination</option>
<option value="clp">CL&P</option>
</select>
<input type="submit" value="Continue">
<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
<?php
} elseif ($userCostCenter === "United Illuminating") {
?>
<form name="OrderForm" action="/confirm" method="POST">
<?php
$query = 'SELECT * FROM Vendors WHERE costCenterID = 1';
$productQuery = 'SELECT * FROM Products WHERE costCenterID = 1';
$results = $db->getAll($query);
$productResults = $db->getAll($productQuery);?>
<table class="table">
<thead>
<tr>
<th>Quantity/Product</th>
<th>Category</th>
<th>Vendor</th>
<th>Address</th>
</tr>
<?php
foreach ($results as $vendor) {
?>
<tr class="category">
<td></td>
<td><?php echo $vendor['Category']; ?></td>
<td><?php echo $vendor['Vendor']; ?></td>
<td><?php echo $vendor['Address']; ?></td>
</tr>
<?php foreach ($productResults as $product) { ?>
<tr class="product">
<td colspan="4"><span class="name"><input type="text" name="quantities[]" size="1" /><?php echo $product['Product'];?></span></td>
</tr>
<?php } ?>
<td><input type="hidden" name="vendor[]" value="<?php echo $vendor['vendorID']; ?>"/></td>
<?php
}?>
</table>
<input type="submit" value="Checkout"<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
</div><?php
}
else {
?>
<form name="OrderForm" action="/confirm" method="POST">
<?php $query = 'SELECT * FROM Vendors Where costCenterID = 2';
$productquery = 'SELECT * FROM Products WHERE costCenterID = 2';
$results = $db->getAll($query);
$productresults = $db->getAll($productquery);?>
<table class="table">
<thead>
<tr>
<th>Quantity/Product</th>
<th>Category</th>
<th>Vendor</th>
<th>Address</th>
</tr>
<?php
foreach ($results as $vendor) {
?>
<tr class="category">
<td></td>
<td><?php echo $vendor['Category'];?></td>
<td><?php echo $vendor['Vendor'];?> </td>
<td><?php echo $vendor['Address'];?></td>
</tr>
<?php
foreach ($productresults as $product){
?>
<tr class="product">
<td colspan="4"><span class="name"><input type="text" name="quantities[<?php echo $vendor['vendorID']; ?>]" size="1" /><?php echo $product['Product'];?></span></td>
<td><input type="hidden" name="vendor[]" value="<?php echo $vendor['vendorID']; ?>"/></td>
</tr>
<?php
}
?>
<?php
}?>
</table>
<input type="submit" value="Checkout"<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
</div><?php
}
?>
This is the confirm page below.
<?php defined('C5_EXECUTE') or die("Access Denied.");
$db= Loader::db();
$quantity = $_POST['quantities'];
$vendor = $_POST['vendor'];
$minimumorder = 25;
foreach($quantity as $num){
if ($num >= $minimumorder){
echo "$num";
echo "</br>";
foreach($vendor as $vendors){
echo "$vendors";
echo "</br>";
}
}
}
?>
I appreciate any help anyone can give. This has had me stumped for a few days actually.
you might want to rearrange your array, and do something like:
$i = 0;
foreach ($productresults as $product) {
echo '<input name="product['.$i.'][quantity]" />';
echo '<input name="product['.$i.'][vendor_id]" value="'.$vendor['vendorID'].'" type="hidden" />';
++$i;
}
The resulting array in $_POST would have the quantities & their vendor separated into their own arrays.
In your code $vendor['vendorID'] seems the key of your $_POST['quantities'] so in your confirm page you could use:
foreach($quantity as $vendorid=>$num){
if ($num >= $minimumorder){
echo "$num";
echo "</br>";
echo "$vendorid";
}
}

Categories