Connecting Radio Button to Database using CodeIgniter - php

I got trouble inputing the radio button value to database, when i choose "submit" it won't add into database. This is the form view:
<?php
$form = array(
'no pengujian' => array(
'name' => 'NO_PENGUJIAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('NO_PENGUJIAN', isset($form_value['NO_PENGUJIAN']))),
'id kendaraan' => array(
'name' => 'ID_KENDARAAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('ID_KENDARAAN', isset($form_value['ID_KENDARAAN']))),
'no kendaraan' => array(
'name' => 'NO_KENDARAAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('NO_KENDARAAN', isset($form_value['NO_KENDARAAN']))),
'lampu' => array(
'name' => 'LAMPU',
'size' => '30',
'class' => 'radio',
'value' => set_value('LAMPU', isset($_POST['LAMPU']))),
'submit' => array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Simpan'
)
);
?>
<h2><?php echo $breadcrumb ?></h2>
<!-- pesan start -->
<?php if (! empty($pesan)) : ?>
<div class="pesan">
<?php echo $pesan; ?>
</div>
<?php endif ?>
<!-- pesan end -->
<!-- form start -->
<?php echo form_open($form_action); ?>
<p>
<?php echo form_label('No Pengujian', 'NO_PENGUJIAN'); ?>
<?php echo form_input($form['no pengujian']); ?>
</p>
<?php echo form_error('NO_PENGUJIAN', '<p class = "field_error">', '</p>');?>
<p>
<?php echo form_label('Id Kendaraan', 'ID_KENDARAAN'); ?>
<?php echo form_input($form['id kendaraan']); ?>
</p>
<?php echo form_error('ID_KENDARAAN', '<p class="field_error">', '</p>'); ?>
<p>
<?php echo form_label('No Kendaraan', 'NO_KENDARAAN'); ?>
<?php echo form_input($form['no kendaraan']); ?>
</p>
<?php echo form_error('NO_KENDARAAN', '<p class="field_error">', '</p>'); ?>
<p>
<?php echo form_label('Lampu', 'LAMPU'); ?>
<input type ="radio" name = "lulus" value="Lulus"/> Lulus
<input type ="radio" name = "lulus" value= "Gagal"/> Gagal
</p>
<p>
<?php echo form_submit($form['submit']); ?>
<?php echo anchor('pengujian', 'Batal', array('class' => 'cancel')) ?>
</p>
<?php echo form_close(); ?>
This is the controller (tambah is "insert" function to database)
<?php if (!defined('BASEPATH')) exit ('No direct script access allowed');
class Pengujian extends MY_Controller
{
public $data = array(
'modul' => 'pengujian',
'breadcrumb' => 'Pengujian',
'pesan' => '',
'pagination' => '',
'tabel_data' => '',
'main_view' => 'view_pengujian/pengujian_view',
'form_action' => '',
'form_value' => '',
'option_uji' => '',
);
public function __construct()
{
parent::__construct();
$this->load->model('Pengujian_model', 'pengujian', TRUE);
$this->load->helper('form');
//$this->load->model('Penguji_model', 'penguji', TRUE);
}
public function index($offset = 0)
{
$this->session->unset_userdata('no_pengujian_sekarang', '');
$pengujian = $this->pengujian->cari_semua($offset);
if ($pengujian)
{
$tabel = $this->pengujian->buat_tabel($pengujian);
$this->data['tabel_data'] = $tabel;
$this->data['pagination'] = $this->pengujian->paging(site_url('pengujian/halaman'));
}
else
{
$this->data['pesan'] = 'Tidak ada data pengujian';
}
$this->load->view('template', $this->data);
}
public function tambah()
{
$this->data['breadcrumb'] = 'Pengujian > Tambah';
$this->data['main_view'] = 'view_pengujian/pengujian_form';
$this->data['form_action'] = 'pengujian/tambah';
//$penguji = $this->penguji->cari_semua();
//if($penguji)
//{
// foreach($penguji as $row)
// {
// $this->data['option_pengujian'][$row->id_penguji] = $row->penguji;
//}
//}
//else
//{
$this->data['option_pengujian']['00'] = '-';
// $this->data['pesan'] = 'Data penguji tidak tersedia. Silahkan isi dahulu data penguji.';
// if submit
if($this->input->post('submit'))
{
if($this->pengujian->validasi_tambah())
{
if($this->pengujian->tambah())
{
$this->session->set_flashdata('pesan', ' Proses tambah data berhasil');
redirect('pengujian');
}
else
{
$this->data['pesan'] = 'Proses tambah data gagal';
$this->load->view('template', $this->data);
}
}
else
{
$this->load->view('template', $this->data);
}
}
else
{
$this->load->view('template', $this->data);
}
}
This is the model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Pengujian_model extends CI_Model
{
public $db_tabel ='pengujian';
public $per_halaman = 100;
public $offset = 0;
public function cari_semua($offset = 0)
{
if (is_null($offset) || empty($offset))
{
$this->offset = 0;
}
else
{
$this->offset = ($offset * $this->per_halaman) - $this->per_halaman;
}
return $this->db->select('NO_PENGUJIAN, ID_KENDARAAN, NO_KENDARAAN, LAMPU, EMISI, REM, WAKTU_UJI')
->from($this->db_tabel)
->limit($this->per_halaman, $this->offset)
->order_by('NO_PENGUJIAN', 'ASC')
->get()
->result();
}
public function buat_tabel($data)
{
$this->load->library('table');
$tmpl = array('row_alt_start' => '<tr class="zebra">');
$this->table->set_template($tmpl);
$this->table->set_heading('No', 'No Pengujian', 'Id Kendaraan', 'No Kendaraan', 'Lampu','Emisi','Rem', 'Waktu Uji', 'Aksi');
$no = 0 + $this->offset;
foreach ($data as $row)
{
$this->table->add_row(
++$no,
$row->NO_PENGUJIAN,
$row->ID_KENDARAAN,
$row->NO_KENDARAAN,
$row->LAMPU,
$row->EMISI,
$row->REM,
$row->WAKTU_UJI,
anchor('pengujian/edit/'.$row->NO_PENGUJIAN,'Edit',array('class' => 'edit')).' '.
anchor('pengujian/hapus/'.$row->NO_PENGUJIAN,'Hapus',array('class' => 'delete','onclick'=>"return confirm('Anda yakin menghapus data ini?')")));
}
$tabel = $this->table->generate();
return $tabel;
}
public function paging($base_url)
{
$this->load->library('pagination');
$config = array(
'base_url' => $base_url,
'total_rows' => $this->hitung_semua(),
'per_page' => $this->per_halaman,
'num_links' => 4,
'use_page_number' => TRUE,
'first link' => '|< First',
'last link' => 'Last >|',
'next link' => 'Next >',
'prev_link' => '< Prev',
);
$this->pagination->initialize($config);
return $this->pagination->create_links();
}
public function hitung_semua()
{
return $this->db->count_all($this->db_tabel);
}
private function load_form_rules_tambah()
{
$form = array(
array(
'field' => 'NO_PENGUJIAN',
'label' => 'no pengujian',
'rules' => 'required'
),
array(
'field' => 'ID_KENDARAAN',
'label' => 'id kendaraan',
'rules' => 'required'
),
array(
'field' => 'NO_KENDARAAN',
'label' => 'no kendaraan',
'rules' => 'required'
),
array(
'field' => 'LAMPU',
'label' => 'lampu',
'rules' => 'required'
),
);
return $form;
}
public function validasi_tambah()
{
$form = $this->load_form_rules_tambah();
$this->form_validation->set_rules($form);
if($this->form_validation->run())
{
return TRUE;
}
else
{
return FALSE;
}
}
public function tambah()
{
$pengujian = array(
'NO_PENGUJIAN' => $this->input->post('NO_PENGUJIAN'),
'ID_KENDARAAN' => $this->input->post('ID_KENDARAAN'),
'NO_KENDARAAN' => $this->input->post('NO_KENDARAAN'),
'LAMPU' => $this->input->post('lampu[]'),
//'EMISI' => $this->input->post('EMISI'),
//'REM' => $this->input->post('REM')
);
$lulus = $_POST["lulus"];
//$statement = "INSERT INTO pengujian VALUES($lulus)"
$this->db->insert($this->db_tabel, $pengujian);
if($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
I got no trouble in the formfield. The trouble is the radio button "lampu"

The best thing to do, I think, is to check where it's going wrong. I usually do this, in this case, by checking if the value is being passed back to the controller and model. This way you understand better what's going on inside your code. Do something like this:
In the model:
public function tambah()
{
// Check to see if we get a value. If not, do the same in the controller
var_dump($this->input->post('lampu'));
exit;
$pengujian = array(
'NO_PENGUJIAN' => $this->input->post('NO_PENGUJIAN'),
'ID_KENDARAAN' => $this->input->post('ID_KENDARAAN'),
'NO_KENDARAAN' => $this->input->post('NO_KENDARAAN'),
'LAMPU' => $this->input->post('lampu[]'),
//'EMISI' => $this->input->post('EMISI'),
//'REM' => $this->input->post('REM')
);
$lulus = $_POST["lulus"];
//$statement = "INSERT INTO pengujian VALUES($lulus)"
$this->db->insert($this->db_tabel, $pengujian);
if($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
I hope this helps a bit....

Related

Rows not found, Codeiginiter Show Index

I'm new with Codeigniter. I got error on my code using Codeigniter. My index doesn't show the row of my datatable, even my datatable had data in it. Anyone can find my error or typo text on my code? Please help me :(.
btw I have 2 controllers.
Here's my first controller (modules->api->controller->Tower.php)
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . '/core/MY_Auth.php';
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class Tower extends MY_Auth
{
protected $ruleMsg;
function __construct()
{
parent::__construct();
$this->load->model('Model_tower');
$this->load->library('Pagingmeta');
$this->load->library('Validate');
$this->ruleMsg = '%s must be filled';
}
public function index_get($id = '') {
if (!empty($id)) {
return $this->get_detail($id);
}
$keyword = $this->get('search', true);
$except = $this->get('excepth', true);
$type = $this->get('type', true)??'list';
$page = $this->get('page', true)??1;
$limit = $this->get('limit', true)??10;
$data = $this->Model_tower->get_list($keyword, $this->role, $this->regional, $page, $limit);
$this->response([
'message' => 'Get tower success',
'data' => $data['data'],
'meta' => $this->pagingmeta->get_meta($data['total'], $limit, $page)
], REST_Controller::HTTP_OK);
}
private function get_detail($id) {
$data = $this->Model_tower->get_detail($id);
if (empty($data)) {
return $this->response([
'message' => 'Data not found'
], REST_Controller::HTTP_BAD_REQUEST);
}
if ($this->regional != $data->regional && $this->role != 'ADMN' && $id != $this->userId) {
return $this->response([
'message' => "You didn't have right to access this data"
], REST_Controller::HTTP_BAD_REQUEST);
}
if ($this->role == 'ADMN') {
$data->is_editable = true;
}
return $this->response([
'message' => 'Get tower success',
'data' => $data
], REST_Controller::HTTP_OK);
}
public function tower_post() {
$this->validate_role();
$rules = $this->rules_post($this->post(null, true));
$params = $this->validate->validation($this->post(null, true), $rules);
if (!$params['status']) {
$this->response([
'message' => $params['errors'][0]
], REST_Controller::HTTP_BAD_REQUEST);
}
$params = $params['data'];
if ($this->Model_tower->validate_site_id($params['site_id'])) {
$this->response([
'message' => 'Site ID already exist'
], REST_Controller::HTTP_BAD_REQUEST);
}
$id = $this->Model_tower->tower_action($params, $this->userId);
$this->response([
'message' => 'Create tower success',
'data' => $id
], REST_Controller::HTTP_CREATED);
}
public function tower_put($id = '') {
$this->validate_role();
$rules = $this->rules_post($this->put(null, true));
$params = $this->validate->validation($this->put(null, true), $rules);
if (!$params['status']) {
$this->response([
'message' => $params['errors'][0]
], REST_Controller::HTTP_BAD_REQUEST);
}
$params = $params['data'];
if ($this->Model_tower->validate_site_id($params['site_id'], $id)) {
$this->response([
'message' => 'Site ID already exist'
], REST_Controller::HTTP_BAD_REQUEST);
}
$this->Model_tower->tower_action($params, $this->userId, $id);
$this->response([
'message' => 'Update tower success',
'data' => $id
], REST_Controller::HTTP_OK);
}
public function upload_post() {
$this->validate_role();
$this->load->library('Uuid');
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($_FILES['data']['tmp_name']);
$sheet = $spreadsheet->getActiveSheet();
// Store data from the activeSheet to the varibale in the form of Array
$data = array_values($sheet->toArray(null,true,true,true));
$oldData = $this->Model_tower->get_all_data();
$oldData = array_column($oldData, 'site_id');
$insertData = [];
$now = date('Y-m-d H:i:s');
foreach($data as $index => $d) {
if ($index == 0) {
continue;
}
$code = $this->uuid->generate();
$type = '';
$regional = '';
$inputedType = $d['D'];
if ($inputedType == 'MTEL') {
$type = 'mtel';
} else {
$type = 'reseller';
}
$inputedRegional = $d['G'];
if ($inputedRegional == 'Jawa Timur') {
$regional = 'JATIM';
} else if ($inputedRegional == 'Jawa Tengah') {
$regional = 'JATENG';
} else {
$regional = 'BALNUS';
}
if (empty($d['A']) || empty($d['B']) || in_array($d['A'], $oldData)) {
break;
}
$insertData[] = [
'site_id' => $d['A'],
'project_id' => $d['B'],
'site_name' => $d['C'],
'type' => $type,
'company' => $d['E'],
'address' => $d['F'],
'regional_code' => $regional,
'active_status' => 1,
'created_at' => $now,
'updated_at' => $now,
'code' => $code,
'created_by' => $this->userId,
'updated_by' => $this->userId
];
}
if (!empty($insertData)) {
$this->Model_tower->insert_batch($insertData);
}
$this->response([
'message' => 'Bulk insert success',
], REST_Controller::HTTP_CREATED);
}
private function validate_role() {
if ($this->role != 'ADMN') {
return $this->response([
'message' => "You didn't have right to access this action"
], REST_Controller::HTTP_BAD_REQUEST);
}
}
private function rules_post() {
return [
[
'field' => 'site_id',
'label' => 'Site id',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'project_id',
'label' => 'Project id',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'name',
'label' => 'Name',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'type',
'label' => 'Type',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'regional',
'label' => 'Regional',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'address',
'label' => 'Address',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'company',
'label' => 'Company',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'status',
'label' => 'Status',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
];
}
}
and this is my second Controller (Controllers->Tower.php)
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . '/core/MY_Cont.php';
class Tower extends MY_Cont
{
public function __construct()
{
parent::__construct();
}
public function index() {
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'List Tower',
'nav_target' => 'tower_list',
);
$this->view('tower/index', $opts);
}
public function detail($code = null) {
if (empty($code)) {
$this->render_invalid();
}
$fetch_detail = $this->get_data_tower($code);
if ($fetch_detail['code'] !== 200) {
$this->render_invalid();
}
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Tower Detail',
'tower' => $fetch_detail['response']->data,
'nav_target' => 'tower_list',
);
$this->view('tower/detail', $opts);
}
public function new() {
$regional = $this->get_regional();
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Add New Tower',
'list_region' => $regional['response']->data,
'nav_target' => 'tower_new',
);
$this->view('tower/new', $opts);
}
public function bulk() {
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Upload Tower',
'nav_target' => 'tower_bulk',
);
$this->view('tower/bulk', $opts);
}
public function edit($code = null) {
if (empty($code)) {
$this->render_invalid();
}
$fetch_detail = $this->get_data_tower($code);
if ($fetch_detail['code'] !== 200) {
$this->render_invalid();
}
$regional = $this->get_regional();
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Edit Tower Detail',
'tower' => $fetch_detail['response']->data,
'list_region' => $regional['response']->data,
'nav_target' => 'tower_list',
);
$this->view('tower/edit', $opts);
}
private function render_invalid() {
header('HTTP/1.0 404');
$opts = array(
'content_only' => true,
'cfg_mainclass' => 'fullpage',
'private_routing' => false,
);
$this->view('layouts/404', $opts);
exit();
}
private function get_data_tower($id = '') {
if (empty($id)) {
$curl = curl_init(base_url() . 'api/tower');
} else {
$curl = curl_init(base_url() . 'api/tower/' . $id);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $this->session->userdata('usertoken'),
));
$result = json_decode(curl_exec($curl));
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array(
'code' => $httpcode,
'response' => $result,
);
}
private function get_regional() {
$curl = curl_init(base_url() . 'api/master/regional');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $this->session->userdata('usertoken'),
));
$result = json_decode(curl_exec($curl));
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = array(
'code' => $httpcode,
'response' => $result,
);
return $response;
}
}
and this is my index.php
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="mainpanel">
<div class="mainpanel-header">
<div class="row align-items-end">
<div class="col-9">
<h3>List Tower</h3>
<h5>Click on tower to view detail</h5>
</div>
<div class="col text-right">
<a href="{{ base_url }}tower/new" class="panel-cta">
Add new tower
</a>
</div>
</div>
</div>
<form method="post" action="" id="form-filter-data" autocomplete="off">
<div class="digi-tablefilter">
<div class="filter-inputholder">
<label>Search</label>
<input type="text" name="search" placeholder="Search keyword" id="filter-search" />
</div>
<div class="filter-inputholder">
<input type="submit" value="Apply filter" />
</div>
</div>
</form>
<span class="table-information" id="t-info"></span>
<div class="digi-tableholder">
<table>
<thead>
<tr>
<th>Name</th>
<th>Project ID</th>
<th>Site ID</th>
<th>Regional</th>
<th>Company</th>
</tr>
</thead>
<tbody id="tower-table-value"></tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div id="test-pag"></div>
</div>
</div>
</div>
</section>
<script>
$(document).ready(function() {
const payload = {
page: 1,
limit: 10,
search: '',
}
fetchListData(payload);
});
function fetchListData(payload) {
var apiURL = "{{ api_server ~ 'tower' }}";
var userToken = getUserToken();
$.ajax({
url: apiURL,
type: "GET",
data: payload,
headers: {
Authorization: userToken,
},
success: function(response) {
const { data, message, meta } = response;
buildDataTable(data, meta);
},
error: function(response) {
const { responseJSON } = response;
addNotification({
type: 'error',
title: 'Fetching data tower gagal',
message: responseJSON.message,
});
return;
}
});
}
function buildDataTable(data, metadata) {
const target = document.getElementById("tower-table-value");
const txtResult = document.getElementById("t-info");
$("#tower-table-value").empty();
target.innerHTML = "";
txtResult.innerHTML = "";
if (data.length == 0) {
buildEmptyRows();
return;
}
$.each(data, function(idx, item) {
const { id, name, project_id, site_id, regional, company } = item;
const tr = document.createElement('tr');
const nameHolder = document.createElement('td');
const projectHolder = document.createElement('td');
const siteHolder = document.createElement('td');
const regionalHolder = document.createElement('td');
const companyHolder = document.createElement('td');
nameHolder.innerHTML = name;
projectHolder.innerHTML = project_id;
siteHolder.innerHTML = site_id;
regionalHolder.innerHTML = regional;
companyHolder.innerHTML = company;
tr.appendChild(nameHolder);
tr.appendChild(projectHolder);
tr.appendChild(siteHolder);
tr.appendChild(regionalHolder);
tr.appendChild(companyHolder);
tr.onclick = function(e) {
window.location.href = `{{ base_url }}tower/detail/${item.id}`;
}
target.appendChild(tr);
});
var $resultText = `Showing result with keyword <strong>${$("#filter-search").val() == '' ? '-' : $("#filter-search").val()}</strong> ${metadata.total} row(s) found.`;
txtResult.innerHTML = $resultText;
if (metadata.last_page > 1) {
buildPagination(metadata);
} else {
hideLoader();
}
}
function buildEmptyRows() {
const target = document.getElementById("tower-table-value");
const txtResult = document.getElementById("t-info");
var $resultText = `Showing result with keyword <strong>${$("#filter-search").val() == '' ? '-' : $("#filter-search").val()}</strong> • 0 row(s) found.`;
txtResult.innerHTML = $resultText;
const tr = document.createElement('tr');
const td = document.createElement('td');
td.colspan = 5;
td.innerHTML = 'No Rows Found.';
tr.appendChild(td);
target.appendChild(tr);
hideLoader();
}
function buildPagination(metadata) {
const { from, to, last_page, current_page, per_page, total } = metadata;
$("#test-pag").pagination({
items: total,
itemsOnPage: per_page,
currentPage: current_page,
onPageClick: function(pageNumber, event) {
event.preventDefault();
const payload = {
page: pageNumber,
limit: per_page,
search: '',
}
fetchListData(payload);
}
});
}
$("#form-filter-data").submit(function(e) {
e.preventDefault();
const $payload = {
page: 1,
limit: 10,
search: $("#filter-search").val()
}
fetchListData($payload);
})
</script>
I'll very thankful if u can solve my problem :D

laravel 5.1 foreach Trying to get property of non-object

i am having 3-4 for each in my code which all use Eloquent and in all of them i get the same error
Trying to get property of non-object
when i dd the first argument of foreach which is an eloquent it returns an array of json with all the data in database of that table so its not returning null though i know it may break or bring null while in a foreach loop but i dont know where place one of them with model and controller here so here is the loop it self
<?php foreach(\App\Menu::all()->where('slug','main')->first()->items as $top_menu): ?>
<li class="dropdown">
<a href="<?php echo e(URL($top_menu->link)); ?>" <?php if($top_menu->link_blank): ?> target="_blank" <?php endif; ?>>
<?php echo e($top_menu->title); ?>
</a>
</li>
<?php endforeach; ?>
and here is my controller
class MenuItemsController extends AdminController
{
var $object = 'menu_items';
var $route_name = 'menu_items';
var $object_title = 'item';
var $object_titles = 'items';
var $attachments_config = [
'main_image' => [],
'default_thumb_sizes' => [],
'require' => ['main_image']
];
var $dt_fields_db = [];
var $dt_fields_heading = ['شناسه','منو','عنوان','موقعیت','نمایش','ثبت','عملیات'];
var $dt_fields_full = [
'id' => ['menu_items.id'],
'menu_title' => ['menus.title'],
'title' => ['menu_items.title'],
'position' => ['menu_items.position'],
'display' => ['menu_items.display'],
'created_at' => ['menu_items.created_at'],
'actions' => ['actions']
];
var $messages = array();
public function __construct() {
parent::__construct();
view()->share(['attachments_config' => $this->attachments_config]);
}
function index() {
$data['extra_assets'] = array(
array('type' => 'css','path' => 'datatables/datatables.bootstrap.css'),
array('type' => 'js','path' => 'datatables/jquery.dataTables.min.js'),
array('type' => 'js','path' => 'datatables/datatables.bootstrap.js'),
array('type' => 'script','path' => 'pagescripts/shared/datatables_script.php'),
);
$data['dt_fields_heading'] = $this->dt_fields_heading;
$data['dt_fields'] = $this->dt_fields_full;
$data['heading'] = $this->object_titles;
return view('admin.shared.datatable',$data);
}
function datatable() {
$this->dt_filtered_actions = dt_actions_filter($this->route_name,['edit','delete']);
$objects = DB::table('menu_items')
->join('menus', 'menu_items.menu_id','=', 'menus.id')
->select([
'menu_items.id',
'menus.title as menu_title',
'menu_items.title',
'menu_items.display',
'menu_items.position',
'menu_items.created_at'
]);
return Datatables::of($objects)
->editColumn('display', function($model) {return label_status($model->display);})
->editColumn('created_at', function($model) {return ($date = jDate::forge($model->created_at)->format('%H:%M:%S - %y/%m/%d'))?$date:"";})
->addColumn('actions', function($model) {
return dt_actions($this->route,$model->id,$this->dt_filtered_actions);
})
->make(true);
}
function add() {
$data['extra_assets'] = array(
array('type' => 'js','path' => 'select2/select2.full.min.js'),
array('type' => 'css','path' => 'select2/select2.min.css'),
array('type' => 'css','path' => 'select2/select2-bootstrap.css'),
array('type' => 'helper','name' => 'select2'),
);
$data['menus'] = Menu::all()->lists('title','id');
$data['heading'] = 'add'.$this->object_title;
return view('admin.'.$this->route_name.'.add',$data);
}
function create(\Illuminate\Http\Request $request) {
$validator = Validator::make($request->all(), [
'menu_id' => 'required',
]);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
$input = $request->all();
$input['display'] = (isset($input['display']))?$input['display']:0;
$menu = Menu::find($input['menu_id']);
if($menu->items->count() == $menu->capacity) {
$this->messages[] = array('type' => 'danger', 'text' => 'menu is full');
Session::flash('messages', $this->messages);
return back();
}
MenuItem::create($input);
$this->messages[] = array('type' => 'success', 'text' => 'success.');
Session::flash('messages', $this->messages);
return redirect()->route('admin.'.$this->route_name.'.index');
}
function edit(MenuItem $MenuItem) {
$data['object'] = $MenuItem;
$data['extra_assets'] = array(
array('type' => 'script','path' => 'pagescripts/shared/image_preview_script.php'),
array('type' => 'js','path' => 'select2/select2.full.min.js'),
array('type' => 'css','path' => 'select2/select2.min.css'),
array('type' => 'css','path' => 'select2/select2-bootstrap.css'),
array('type' => 'helper','name' => 'select2'),
array('type' => 'js','path' => 'ckeditor/ckeditor.js'),
array('type' => 'js','path' => 'ckeditor/config.js'),
array('type' => 'js','path' => 'ckfinder/ckfinder.js'),
array('type' => 'js','path' => 'ckfinder/config.js'),
array('type' => 'script','path' => 'pagescripts/shared/ckeditor_script.php'),
);
$data['menus'] = Menu::all()->lists('title','id');
$data['heading'] = 'edit'.$this->object_title;
return view('admin.'.$this->route_name.'.edit',$data);
}
function update(MenuItem $MenuItem,\Illuminate\Http\Request $request) {
$validator = Validator::make($request->all(), [
'menu_id' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
$input = $request->all();
$input['display'] = (isset($input['display']))?$input['display']:0;
$MenuItem->update($input);
$this->messages[] = array('type' => 'success', 'text' => 'success.');
Session::flash('messages', $this->messages);
return redirect()->back();
}
function delete(\Illuminate\Http\Request $requests,MenuItem $MenuItem) {
if($requests->ajax() && $MenuItem->delete()) {
return "OK";
} else {
return "ERROR";
}
}
function deleteall(\Illuminate\Http\Request $requests) {
$ids = $requests->get('ids');
if($requests->ajax()) {
foreach (explode(',',$ids) as $id) {
if(intval($id)) MenuItem::find($id)->delete();
}
return "OK";
} else {
return "ERROR";
}
}
}
the problem was because my database table didn't got any row by the slug of menu and the query returned null and that error happens that error generally happens when your query returns null thanks all for help

How to upload image in codeigniter

controller:
public function edit($id) {
$this->edit_status_check($id);
$this->form_validation->set_rules('agent_name', 'Agent Name', 'required');
$this->form_validation->set_rules('mobile', 'Mobile No.', 'required');
$this->form_validation->set_rules('agent_vehicle', 'Agent Vehicle', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => validation_errors(),
'id' => $id
);
$this->load->view('template', $data);
} else {
$config['upload_path'] = '../uploads/agent/';
$config['allowed_types'] = 'jpg|jpeg';
$config['encrypt_name'] = TRUE;
$config['max_size'] = 1000; // 1 mb
$this->load->library('upload', $config);
if (!$this->upload->do_upload('agent_image')) {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => $this->upload->display_errors(),
'id' => $id
);
$this->load->view('template', $data);
} else {
$_POST['agent_img_url'] = 'uploads/agent/' . $this->upload->data('file_name');
$this->agent_model->update($_POST, $id);
alert('Update', $_POST['agent_name']);
redirect('agent');
}
}
}
Model:
public function update($data, $id) {
$updatedata = array(
'name' => $data['agent_name'],
'mobile' => $data['mobile'],
'password' => sha1($data['password']),
'vehicle' => $data['agent_vehicle'],
'address' => $data['agent_address'],
'category' => $data['category'],
'created_on' => date('Y-m-d h:i:sa')
);
if (!empty($data['agent_img_url'])) {
$updatedata['img_url'] = $data['agent_img_url'];
}
$this->db->where('id', $id);
$this->db->update('agent', $updatedata);
}
View:
<?= form_open_multipart('agent/edit/' . $id); ?>
<?php if (!empty($error)): ?>
<div class="alert alert-danger alert-dismissible" role="alert">
<?= $error; ?>
</div>
<?php endif; ?>
<div class="form-group">
<img src="/<?= $result['img_url']; ?>" class="img-responsive" name="old_agent_image" width="133" height="100">
</div>
<div class="form-group">
<label>Agent Image</label>
<input type="file" name="agent_image">
</div>
<button type="submit" class="btn btn-success">Update</button>
<?= form_close(); ?>
Hi I'm developing a image upload module and image path save in database and retrieve.
my Question I want it to edit and update but the my problem is it doesn't delete the old image in folder, but it save and update the new image.
use file helper of codeigniter
$this->load->helper("file");
delete_files($path);
reference link for you is here
Delete using the file name saved in the database, use the PHP unlink(../filename.jpg) and delete from files
Change in Model
public function update($data, $id) {
$updatedata = array(
'name' => $data['agent_name'],
'mobile' => $data['mobile'],
'password' => sha1($data['password']),
'vehicle' => $data['agent_vehicle'],
'address' => $data['agent_address'],
'category' => $data['category'],
'created_on' => date('Y-m-d h:i:sa')
);
if (!empty($data['agent_img_url'])) {
$updatedata['agent_img_url'] = $data['agent_img_url'];
}
$q = $this->db->where('id',$id)
->get('agent');
$query = $q->row_array();
#unlink("./asset/uploads/".$query['agent_img_url']);
$this->db->where('id', $id);
$this->db->update('agent', $updatedata);
}
if (!$this->upload->do_upload($name)) {
$data = array('msg' => $this->upload->display_errors());
} else {
$data = array('msg' => "success");
$databasea['upload_data'] = $this->upload->data();
$this->load->library('image_lib');
return $databasea['upload_data']['file_name'];
}
return '';

update statement breaking the database

I am trying to figure out what's wrong here, but really not sure. I have a site with users, when a user edits details, it seems to override all other records with those details. This doesn't happen always but sometimes (of course the result is chaos!). Here is the code of update
public function update_edit()
{
/* echo " //// INSIDE UPDATE EDIT "; */
$this->form_validation->set_rules('fullname', 'الاسم الكامل', 'isset|required|min_length[6]|max_length[100]');
//check that there are no form validation errors
if($this->form_validation->run() == FALSE)
{
/* echo " //// INSIDE FORM VALIDATION"; */
if(($this->session->userdata('username')!=""))
{
/* echo " //// INSIDE SESSION VALIDATION"; */
$data = array();
$data = $this->profileModel->load_user_editable_data($this->session->userdata('username'));
$this->load->view('layout/header');
$this->load->view('profile_edit', $data);
$this->load->view('layout/footer');
//$this->load->view('thankyou');
}else{
//$this->load->view('login');
$this->login();
}
}else{
$complete = $this->profileModel->update_profile($this->session->userdata('username'));
if($complete == 1)
{
$this->load->view('layout/header');
$this->load->view('update_complete');
$this->load->view('layout/footer');
}
}
}
This is the model code:
public function update_profile($username)
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$fullImagePath;
if (isset($_FILES['profilepic']) && !empty($_FILES['profilepic']['name']))
{
if ($this->upload->do_upload('profilepic'))
{
$upload_data = $this->upload->data();
$fullImagePath = '/uploads/' . $upload_data['file_name'];
}
}else{
$fullImagePath = $this->session->userdata('profilepic');
}
$data = array(
'fullname' => $this->input->post('fullname'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'telephone' => $this->input->post('telephone'),
'about' => $this->input->post('about'),
'address' => $this->input->post('address'),
'profilepic' => $fullImagePath,
);
$this->db->where('username', $username);
$this->db->update('free_user_members', $data);
return 1;
}
and this is the form:
<div class="content_container">
<div id="rt-main" class="mb8-sa4">
<div class="rt-container">
<div class="rt-grid-12">
<div dir="rtl" class="homecontent">
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('profile/update_edit'); ?>
<? $this->session->set_userdata('profilepic', $profilepic); ?>
<h5>الاسم الكامل</h5>
<? $data = array(
'name' => 'fullname',
'id' => 'round_input',
'value' => $fullname,
);
echo form_input($data); ?>
<h5>الايميل</h5>
<? $data = array(
'name' => 'email',
'id' => 'round_input',
'value' => $email,
'size' => '70'
);
echo form_input($data); ?>
<h5>الجوال</h5>
<? $data = array(
'name' => 'mobile',
'id' => 'round_input',
'value' => $mobile,
);
echo form_input($data); ?>
<h5>هاتف</h5>
<? $data = array(
'name' => 'telephone',
'id' => 'round_input',
'value' => $telephone,
);
echo form_input($data); ?>
<h5>العنوان</h5>
<? $data = array(
'name' => 'address',
'id' => 'round_input',
'value' => $address,
'size' => '70'
);
echo form_input($data); ?>
<h5>نبذة عني</h5>
<? $data = array(
'name' => 'about',
'id' => 'round_input',
'value' => $about,
'rows' => '3',
'cols' => '40',
);
echo form_textarea($data); ?>
<h5>الصورة الشخصية</h5>
<img width="300" height="300" src="<? echo $profilepic; ?>" />
<h5>إختيار صورة جديدة</h5>
<?
$data = array(
'name' => 'profilepic',
'id' => 'profilepic',
);
echo form_upload($data);
?>
<div><input type="submit" value="احفظ التغييرات" /></div>
</form>
</div>
<p> </p>
</div>
</div>
<div class="clear"></div>
</div>
</div>
will really appreciate it if someone tells me what I am doing that could lead to that chaos every now and then.
Regards,
You have to add code to check that username in the session exists.
If the session times out, codeigniter will return FALSE.
Querying MySQL on username = false will return all rows.

Edit Page -> Loading A Blank White Page

I have an issue when I click on a link to edit a sale http://domain/admin/editsale/index/21/sale-name I seem to get a blank page loaded so I have a feeling that it is not getting the $id but I cannot spot my issue.
Controller:
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Editsale extends CI_Controller {
function __construct() {
parent::__construct();
}
function index($id) {
if(!$this->session->userdata('logged_in'))redirect('admin/home');
if($this->input->post('submit')) {
#Set The Validation Rules
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('location', 'Location', 'trim|required');
$this->form_validation->set_rules('bedrooms', 'Bedrooms', 'trim|is_natural');
$this->form_validation->set_rules('bathrooms', 'Bathrooms', 'trim');
$this->form_validation->set_rules('condition', 'Condition', 'trim');
$this->form_validation->set_rules('description', 'Description', 'trim');
$this->form_validation->set_rules('price', 'Price', 'trim');
if($this->form_validation->run() == FALSE) {
#Set the $data for the view if FALSE
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
$data['sales_pages'] = $this->sales_model->getSalesPages($id);
$data['sale'] = $this->sales_model->getSalesContent($id);
$data['content'] = $this->load->view('admin/editsale', $data, TRUE); #Loads the "content"
$this->load->view('admintemplate', $data); #Loads the given template and passes the $data['content'] into it
}
#Form Validation Was Correct So Lets Continue
#Lets Set What We Are Sending To The DB
$content = array(
'name' => $this->input->post('name', TRUE),
'location' => $this->input->post('location', TRUE),
'bedrooms' => $this->input->post('bedrooms', TRUE),
'bathrooms' => $this->input->post('bathrooms', TRUE),
'condition' => $this->input->post('condition', TRUE),
'description' => $this->input->post('description', TRUE),
'price' => $this->input->post('price', TRUE)
);
if($this->sales_model->updateSale($id, $content)) {
$data['success'] = TRUE; #displays sale updated
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
$data['sales_pages'] = $this->sales_model->getSalesPages($id);
$data['sale'] = $this->sales_model->getSalesContent($id);
$data['content'] = $this->load->view('admin/editsale', $data, TRUE); #Loads the "content"
} // Sale Update End
}else{
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
$data['sales_pages'] = $this->sales_model->getSalesPages($id);
$data['sale'] = $this->sales_model->getSalesContent($id);
$data['content'] = $this->load->view('admin/editsale', $data, TRUE); #Loads the "content"
}#Submit End
} #Index End
}
Model:
function getSalesPages($id = NULL) {
$query = $this->db->get('sales');
if($query->num_rows() > 0) return $query->result();
}
function getSalesContent($id = NULL) {
$this->db->where('id', $id);
$query = $this->db->get('sales', 1);
if($query->num_rows() > 0) {
$row = $query->result_array();
return $row;
}else{
return FALSE;
}
}
View:
<?php
//Setting form attributes
$formEditSale = array('id' => 'editSale', 'name' => 'editSale');
$formName = array('id' => 'name', 'name' => 'name');
$formLocation = array('id' => 'location', 'name' => 'location');
$formBedrooms = array('id' => 'bedrooms','name' => 'bedrooms');
$formBathrooms = array('id' => 'bathrooms','name' => 'bathrooms');
$formCondition = array('id' => 'condition','name' => 'condition');
$formDescription = array('id' => 'description','name' => 'description');
$formPrice = array('id' => 'price','name' => 'price');
if($success == TRUE) {
echo '<section id = "validation">Sale Updated</section>';
}
?>
?>
<section id = "validation"><?php echo validation_errors();?></section>
<?php
echo form_open_multipart('admin/editsale/index/'.$sale[0]['id'].'/'.url_title($sale[0]['name'],'dash', TRUE),$formEditSale);
echo form_fieldset();
echo form_label('Name:', 'name');
echo form_input($formName, $sale[0]['name']);
echo form_label ('Location', 'location');
echo form_input($formLocation, $sale[0]['location']);
echo form_label ('Bedrooms', 'bedrooms');
echo form_input($formBedrooms, $sale[0]['bedrooms']);
echo form_label ('Bathrooms', 'bathrooms');
echo form_input($formBathrooms, $sale[0]['bathrooms']);
echo form_label ('Condition', 'condition');
echo form_input($formCondition, $sale[0]['condition']);
echo form_label ('Price', 'price');
echo form_input($formPrice, $sale[0]['sale']);
echo form_label ('Description', 'description');
echo form_textarea($formDescription, $sale[0]['description']);
echo form_submit('submit','Submit');
echo form_fieldset_close();
echo form_close();
Fixed, I was loading the view before the data

Categories