How to insert looping radio button value into db - php

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

Related

Ajax Mysql PHP How to show $_SESSION arrays result into DIV

My friends,
I´m facing some hard trouble with Ajax & PHP integration. I have a simple code as below that returns the data from database and shows into div class="item-list". When the user puts the quantity and clicks on submit button, the selected item is uploaded into div class="returned", like the "add item to cart" function. The code is working as well (add & remove from list), but only with refresh on page.
I saw many examples on web and I tried to adapt them to my code (today is my third day of fighting), but with no success. Could you please show to me a way to load the selected items into div class="returned" without refresh on page?
Best regards & thanks a lot!
<?php
session_start();
if(isset($_POST["add_to_table"])){
if(isset($_SESSION["dynamic_list"])){
$item_array_id = array_column($_SESSION["dynamic_list"], "item_id");
if(!in_array($_GET["idproduct"], $item_array_id)){
$count = count($_SESSION["dynamic_list"]);
$item_array = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["dynamic_list"][$count] = $item_array;
}else{
echo'<script>alert("Item added!")</script>';
echo'<script>window.location="intransit.php"</script>';
}
}else{
$item_array = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["dynamic_list"][0] = $item_array;
}
}
if(isset($_GET["action"])){
if($_GET["action"] == "delete"){
foreach($_SESSION["dynamic_list"] as $list => $values){
if($values["item_id"] == $_GET["idproduct"]){
unset($_SESSION["dynamic_list"][$list]);
echo'<script>alert("Item removed!")</script>';
echo'<script>window.location="intransit.php"</script>';
}
}
}
}
?>
<?php include"header.php" ?>
<div id="main_box">
<div id="moviment">
<div class="item_list">
<?php
$query = "SELECT * FROM products ORDER BY model ASC LIMIT 3";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<div id="product_table">
<form method="post" action="intransit.php?action=add&idproduct=<?php echo $row["idproduct"]; ?>">
<span><img src="images/<?php echo $row["image"]; ?>" alt="motor" width="80" height="80" /></span>
<span>Model:&nbsp<?php echo $row["model"]; ?></span>
<span>Price:&nbsp<?php echo $row["unitprice"]; ?></span>
<input type="text" name="quantity" value="1" class="qty" />
<input type="hidden" name="got_model" value="<?php echo $row["model"]; ?>" />
<input type="hidden" name="got_price" value="<?php echo $row["unitprice"]; ?>" />
<input type="submit" name="add_to_table" value="Add Item" />
</form>
</div><!--end "product_table"-->
<?php
}
}
?>
</div><!--end "item_list"-->
<div class="returned">
<table>
<tr>
<th>Model</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
<th>Action</th>
</tr>
<?php
if(!empty($_SESSION["dynamic_list"])){
$total = 0;
foreach($_SESSION["dynamic_list"] as $list => $values){
?>
<tr>
<td><?php echo $values["model"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td>$<?php echo $values["price"]; ?></td>
<td><?php echo number_format($values["item_quantity"] * $values["price"], 2); ?></td>
<td>Remove</td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2);?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</div>
<?php include"footer.php" ?>
I tried to make example less complicated and to make it work with code you already created.
if (isset($_POST['got_model'])) {
$_SESSION["dynamic_list"][$_GET["idproduct"]] = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
return show_dynamic_list();
}
if (isset($_POST["action"]) && $_POST["action"] == "delete") {
unset($_SESSION["dynamic_list"][$_POST["idproduct"]]);
return show_dynamic_list();
}
function show_dynamic_list(){
?>
<table>
<tr><th>Model</th><th>Qty</th><th>Price</th><th>Total</th><th>Action</th></tr>
<?php
$total = 0;
foreach ($_SESSION["dynamic_list"] as $list => $values) {
?>
<tr>
<td><?php echo $values["model"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td>$<?php echo $values["price"]; ?></td>
<td><?php echo number_format($values["item_quantity"] * $values["price"], 2); ?></td>
<td>
<form action="" method="post" class="delete_form">
<input type="hidden" name="idproduct" value="<?php echo $values["item_id"]; ?>"/>
<input type="hidden" name="action" value="delete"/>
<input type="submit" value="Remove">
</form>
</td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
</table>
<?php
}
include"header.php" ?>
<div id="main_box">
<div id="moviment">
<div class="item_list">
<?php
$query = "SELECT * FROM products ORDER BY model ASC LIMIT 3";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<div id="product_table_<?php echo $row["idproduct"]; ?>">
<form method="post" action="?action=add&idproduct=<?php echo $row["idproduct"]; ?>">
<span>Model:&nbsp<?php echo $row["model"]; ?></span>
<span>Price:&nbsp<?php echo $row["unitprice"]; ?></span>
<input type="text" name="quantity" value="1" class="qty"/>
<input type="hidden" name="got_model" value="<?php echo $row["model"]; ?>"/>
<input type="hidden" name="got_price" value="<?php echo $row["unitprice"]; ?>"/>
<input type="submit" name="add_to_table" value="Add Item"/>
</form>
</div><<!--end "product_table"-->
<?php
}
}
?>
</div><!--end "item_list"-->
<div class="returned">
<?php show_dynamic_list(); ?>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(function () {
$('body').on('submit','#moviment form,.delete_form',function (event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type:'post',
url: form.attr('action'),
data: form.serialize(),
dataType:'html'
}).done(function (data) {
$('.returned').html(data);
}).fail(function (data) {
// error
});
});
});
</script>
<?php include"footer.php";

Delete multiple image from database also database using codeigniter

I just created code that deletes an image from database and also from folder which is an image store, but only one image is successfully deleted from thedatabase and folder when I click "check all". What did I do wrong? Here is my view using check box javascript:
<form name="indonesia" action="<?php echo site_url('admin/wallpaper/delete'); ?>" method="post">
<button type="submit" class="btn btn-danger" name="hapus" value="hapus">Hapus</button>
<?php echo anchor('admin/wallpaper/tambah', 'Tambah Wallpaper');?>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>
<button type="button" class="btn btn-info" onClick="check_all()" >Check</button>
<button type="button" class="btn btn-success" onClick="uncheck_all()" >Un-Check</button>
</th>
<th>id</th>
<th>Keterangan</th>
<th>Gambar</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
foreach ($ListWallpaper->result() as $row)
{
?>
<tr>
<td><input type="checkbox" name="item[]" id="item[]" value="<?=$row->id_wall ?>"></td>
<td><?=$row->id_wall ?></td>
<td><?=$row->ket ?></td>
<td><?=$row->wall ?></td>
<td>
Delete
Update
</td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
and here is my controller
public function delete()
{
$ownerNames = $this->input->post('item');
foreach ($ownerNames as $ownerName => $k) {
//echo "Array : " . $k . "<br/>";
$photo = $this->wallpaper_model->del_photo($k);
if ($photo->num_rows() > 0)
{
$row = $photo->row();
$file_photo = $row->wall;
echo "$file_name</br>";
$path_file = 'image/wallpaper/';
unlink($path_file.$file_photo);
}
$this->wallpaper_model->drop_photo($k);
redirect('admin/wallpaper','refresh');
}
}
and my model
function del_photo($k)
{
$this->db->where('id_wall',$k);
$query = $getData = $this->db->get('tabel_wall');
if($getData->num_rows() > 0)
return $query;
else
return null;
}
function drop_photo($k)
{
$this->db->where('id_wall',$k);
$this->db->delete('tabel_wall');
}
Only one image is successfully deleted from the folder and database too, but when I try to echo "$file_name</br>"; it show all images. What did I do wrong? if anyone can guide me, I will appreciate that.
First off I would set a array of images from controller to view, $data['wallpapers'] = array(); for some of the site_url you may need to include in your route.php $route['controller/update/(:any)'] = "controller/update/$1"
To Delete selected images, You could do a selected post in array() and then on the value check box name=""
Disclaimer: This is just for a example only.
public function index() {
$k = $this->uri->segment(what ever); // Use uri segment is id example.com/image/1 = $this->uri->segment(2);
$results = $this->model_name->del_photo($k);
$data['wallpapers'] = array();
foreach ($results as $result) {
$data['wallpapers'][] = array(
'id_wall' => $result['id_wall'],
'update' => site_url('controllername/update' .'/'. $result['wall_id']),
'ket' => $result['ket']
);
}
$data['delete'] = site_url('controller/function');
$selected = $this->input->post('selected');
if (isset($selected)) {
$data['selected'] = (array)$selected;
} else {
$data['selected'] = array();
}
$this->load->view('your list', $data);
}
public function update() {
//update info here
}
public function delete() {
$selected = $this->input->post('selected');
if (isset($selected)) {
foreach ($selected as $image_id) {
$wall_id = $image_id
$this->db->query("DELETE FROM " . $this->db->dbprfix . "TABLENAME WHERE wall_id = '" . (int)$wall_id . "'");
}
}
}
View
Added echo delete from controller as site url.
<form action="<?php echo $delete;?>" method="post">
<table>
<thead>
<tr>
<td style="width: 1px;" class="text-center"><input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" /></td>
<td>Update</td>
</tr>
</thead>
<tbody>
<?php if ($wallpapers) { ?>
<?php foreach ($wallpapers as $wallpaper) { ?>
<td class="text-center"><?php if (in_array($wallpaper['id_wall'], $selected)) { ?>
<input type="checkbox" name="selected[]" value="<?php echo $wallpaper['id_wall']; ?>" checked="checked" />
<?php } else { ?>
<input type="checkbox" name="selected[]" value="<?php echo $wallpaper['id_wall']; ?>" />
<?php } ?>
</td>
<td>Update</td>
<?php } ?>
<?php } ?>
</tbody>
</table>
</form>
Model
function del_photo($k) {
$this->db->where('id_wall',$k);
$query = $this->db->get('table_name');
if($query->num_rows() > 0) {
$return = $query->result_array();
} else {
return false;
}
}
In controller, move redirect directive outside of foreach loop.

After clicking on a radio button, is it possible to make a new option pop up?

When the user is browsing my system, the user would reach the page where he will choose a shipping option, which is currently using radio buttons. The list is from the database. What I need is:
when the user clicks an option, which is a picture by the way, not a standard radio button, another option will popup, to allow the user to choose a payment option, which is also in my database. I just need to make it pop up so the user will have two values to pass to the other page, namely for $carrier and $payment.
<?php
echo "<table><tr>";
$i = 0;
$qry="SELECT * FROM shipping";
$result= #mysql_query($qry);
while ($row=mysql_fetch_assoc($result)){
if ($i > 0 && $i % 3 == 0) {
echo "</tr><tr>";
}
echo "<td>";
?>
<table width="" cellpadding="3" cellspacing="0" border="1">
<tr class="row_submit">
<td height="250px" width="300px"><center><label>
<input type="radio" name="carrier" <?php if (isset($carrier) && $carrier=="row[ship_name]") echo "checked";?> value="<?php echo $row['ship_name']; ?>">
<!--<img src="../paymentoptions/lbc.png" alt="LBC" class="picture" width="245px" style="margin:10px"/></label></td> -->
<?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['ship_pic'] ).'" height="210px" width="245px" style="margin:10px"/>'; ?>
</tr>
<tr class="row_submit">
<td height="180px" width="300px"><p><?php echo $row['ship_desc']; ?><p></td>
<tr>
<td>
<div id='price'> Additional ₱ <?php echo $row['ship_price']; ?></div></td></tr>
</table>
<?php
echo "</td>";
$i++;
}
echo "</tr></table>";
?>

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";
}
}

How to get several data from a form?

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.

Categories