How to update and delete data from table? - php

I'm new to codeigniter and I want to update and delete a data from the table. Can someone help solve this?I've tried other options but wasn't successful.
Here's my view:
<script>
function show_confirm(act) {
if (act == "edit")
var r = confirm("Do you really want to edit this?");
else
var r = confirm("Do you really want to delete this?");
if (r==true){
window.location="<?php echo base_url(); ?>site/"+act;
}
}
</script>
<style>
select{
position: absolute;
left: 35%;
height: 5%;
width: 33%;
border-radius: 5px;
font-family: arial;
}
table {
background: #333;
width: 700px;
border-collapse: 1px;
font-family: arial;
position: absolute;
top: 33%;
left: 25%;
color: #777;
}
th {
padding-top: 10px;
padding-bottom: 10px;
}
td {
background: #999;
padding: 10px;
text-align: center;
font-size: 12px;
}
.data {
color: #555;
}
.data:hover {
background: #FFF;
}
#action {
font-weight: bold;
color: #444;
text-decoration: none;
}
#action:hover {
color: #FFF;
}
</style>
</head>
<body>
<header>
<div class="menu">
<h1 class="sis">SIS</h1>
<p class="welcome">Welcome!&nbsp &nbsp| &nbsp</p>
<p class="logout">Logout</p>
<nav class="navi">
<ul>
<li>Home</li>
<li>About
<ul class="about">
<li>Vision/Mission</li>
<li>History</li>
</ul>
</li>
<li>Admission</li>
<li>Calendar</li>
<li>Students
<ul class="stud">
<li>Grade I</li>
<li>Grade II</li>
<li>Grade III</li>
<li>Grade IV</li>
<li>Grade V</li>
<li>Grade VI</li>
<li>Academic Records</li>
</ul>
</li>
<li>Teachers
<ul class="teach">
<li>Gradesheet</li>
<li>Lesson Plan</li>
</ul>
</li>
<li>Contact Us</li>
</ul>
</nav>
</div>
</header>
<header>
<div class="container">
<select>
<option placeholder="section"></option>
<option value="section">Section I</option>
<option value="section">Section II</option>
<option value="section">Section III</option>
<option value="section">Section IV</option>
<option value="section">Section V</option>
<option value="section">Section VI</option>
</select>
<table>
<tr id="field">
<th scope="col"> ID </th>
<th scope="col"> First Name </th>
<th scope="col"> Last Name </th>
<th scope="col"> Contact # </th>
<th scope="col"> Address </th>
<th scope="col" colspan="2"> Action </th>
</tr>
<?php foreach ($user_list as $u_key) { ?>
<tr class="data" >
<td><?php echo $u_key->ID; ?></td>
<td><?php echo $u_key->FNAME; ?></td>
<td><?php echo $u_key->LNAME; ?></td>
<td><?php echo $u_key->CONTACT; ?></td>
<td><?php echo $u_key->ADDRESS; ?></td>
<td width="40" align="left"><a id="action" href="#" onClick="show_confirm('edit',<?php echo $u_key->ID; ?>)">Edit</a></td>
<td width="40" align="left"><a id="action" href="#" onClick="show_confirm('delete',<?php echo $u_key->ID; ?>)">Delete</a></td>
</tr>
<?php } ?>
</table>
</div>
</header>
</body>
</html>
My Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Site extends CI_Controller {
public function index(){
$this->home();
$this->load->helper('url');
}
public function home(){
$data['title'] = "Home";
$this->load->view("view_main");
}
function vismis(){
$data['title'] = "Vismis";
$this->load->view("view_vismis");
}
function history(){
$data['title'] = "History";
$this->load->view("view_history");
}
function admission(){
$data['title'] = "Admission";
$this->load->view("view_admission");
}
function contact(){
$data['title'] = "Contact";
$this->load->view("view_contact");
}
function calendar($year = null, $month = null){
$data['title'] = "Calendar";
if(!$year) {
$year = date('Y');
}
if(!$month) {
$month = date('m');
}
$this->load->model('cal_model');
if ($day = $this->input->post('day')) {
$this->cal_model->add_cal_data(
"$year-$month-$day",
$this->input->post('data')
);
}
$data['calendar'] = $this->cal_model->generate($year, $month);
$this->load->view("view_calendar",$data);
}
public function gradeI(){
$this->load->model('stud_model');
$data['title'] = "gradeI";
$data['user_list'] = $this->stud_model->get_users();
$this->load->view('view_students', $data);
}
function add_stud(){
$this->load->model('stud_model');
$udata['fname'] = $this->input->post('fname');
$udata['lname'] = $this->input->post('lname');
$udata['contact'] = $this->input->post('contact');
$udata['address'] = $this->input->post('address');
$res = $this->stud_model->insert_user_to_db($udata);
if ($res){
header('location:'.base_url()."site/gradeI");
}
}
public function edit() {
$this->load->model('stud_model');
$data['title'] = "edit";
$id = $this->uri->segment(3);
$data['user'] = $this->stud_model->getById($id);
$this->load->view('view_editstud', $data);
}
public function update_stud() {
$mdata['fname'] = $_POST['fname'];
$mdata['lname'] = $_POST['lname'];
$mdata['contact'] = $_POST['contact'];
$mdata['address'] = $_POST['address'];
$res = $this->stud_model->update_info($mdata, $_POST['id']);
if($res) {
header('location'.base_url()."site/gradeI");
}
}
public function delete() {
$this->load->model('stud_model');
$id = $this->uri->segment(3);
$res = $this->stud_model->del_stud($id);
if ($res) {
header('location:'.base_url()."site/gradeI");
}
}
function gradeII(){
$this->load->model('stud_model');
$data['title'] = "gradeII";
$data['user_list'] = $this->stud_model->get_users();
$this->load->view('view_stud_two',$data);
}
function gradeIII(){
$data['title'] = "gradeIII";
$this->load->view('view_students');
}
function gradeIV(){
$data['title'] = "gradeIV";
$this->load->view('view_students');
}
function gradeV(){
$data['title'] = "gradeV";
$this->load->view('view_students');
}
function gradeVI(){
$data['title'] = "gradeVI";
$this->load->view('view_students');
}
function acadrecs(){
$data['title'] = "acadrecs";
$this->load->view('view_acadrecs');
}
public function enroll(){
$data['title'] = "enroll";
$this->load->view('view_enroll');
}
}
and my Model:
<?php
class Stud_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database("sis");
}
public function get_users() {
$query = $this->db->get('students');
return $query->result();
}
public function insert_user_to_db($udata) {
return $this->db->insert('students', $udata);
}
public function getById($id) {
$query = $this->db->get_where('students', array('id'=>$id));
return $query->row_array();
}
public function update_info($data, $id) {
$this->db->where('ID', $id);
return $this->db->update('students', $data);
}
public function del_stud($id) {
$this->db->where('ID', $id);
return $this->db->delete('students');
}
}
nothing happens when I click on delete.
On the edit link...
The view:
<form method="post" action="<?php echo base_url();?>site/update_stud">
<?php extract($user); ?>
<table>
<tr>
<th scope="row">Enter your first name</th>
<td><input type="text" name="fname" size="20" value="<?php echo $fname; ?>" /></td>
</tr>
<tr>
<th scope="row">Enter your last name</th>
<td><input type="text" name="lname" size="20" value="<?php echo $lname; ?>" /></td>
</tr>
<tr>
<th scope="row">Enter your contact number</th>
<td><input type="text" name="contact" size="20" value="<?php echo $contact; ?>" /></td>
</tr>
<tr>
<th scope="row">Enter your address</th>
<td><textarea name="address" rows="5" cols="20"><?php echo $address; ?> </textarea></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="submit" name="submit" value="Update" /></td>
</tr>
</table>
This error will show up:
Enter your first name A PHP Error was encountered
Severity: Notice
Message: Undefined variable: fname
Filename: views/view_editstud.php
Line Number: 60
" />
and so on with other input types.

Firstly, neither of the javascript confirm links will work because you're not actually passing the id through with the act:
<script>
function show_confirm(act, id) {
if (act == "edit") {
var r = confirm("Do you really want to edit this?");
} else {
var r = confirm("Do you really want to delete this?");
}
//Just FYI, the above can be written like this:
//var r = (act == 'edit') ? confirm("Do you really want to edit this?") : confirm("Do you really want to delete this?");
//or even
//var r = confirm("Do you really want to "+act+" this?");
if (r == true) {
window.location = "<?php echo base_url(); ?>site/" + act + "/" + id;
}
//Another FYI, the above could be written like this:
// !r || window.location = "<?php echo base_url(); ?>site/" + act + "/" + id;
}
</script>
Obviously, you can delete the comments.
Secondly, you don't need to use $this->uri->segment() to pass params to a controller method as codeigniter will automatically pass them (Unless you're using URI ROUTING), you can instead:
public function delete($id)
{
$this->load->model('stud_model');
$res = $this->stud_model->del_stud($id);
//There is no point in this if statement as it will just display a
//blank page if $res evaluates to FALSE
if ($res) {
//As you aren't using a variable below you might as well use single quotes
//Also, instead of using header('Location') you should use redirect() with codeiginiter
redirect('site/gradeI');
}
}
Lastly, you should really think about validation e.g. codeigniters built in Form_validation Library.
Hope this helps!

Related

My php while loop is not parsing the whole table

I have two tables in my webpage, each being populated with a php while loop.
My first table gets all its data outputted but my second while loop only outputs as many fields as the first one.
My second while loop is not nested within the other one, they are both independent from each other.
When i check the console I see that my second while loops seems to have outputted my data but when I click on my button to display the entire column, only 3 values appear instead of all of them
This is what is shown when I click on TEAM TASK
https://imgur.com/4FCu1dX
This is what is shown when I click on MY TASK
https://imgur.com/q1F6sgx
I also noticed that whether I click on MYTASK or TEAM TASK their are two rows from MYTASK that are always shown.
I Initially had both while loops within the same table but then moved them to each fill there own table but this issue still occurs.
<table border='0' style="float:left; width:20%; height: 500px; border-radius: 5px; display: block;" bgcolor="#2B4353">
<thead>
<tr>
<td bgcolor="#2B4353" border="0" valign="top" align="right">
<div class="messages-header-my" onclick="myTasks()"><p id="myTasks">MY TASKS</p></div></td>
</tr>
</thead>
<tbody>
<?php
while($row8 = mysqli_fetch_array($TableMY)){ $task1234=$row8[1];
?>
<tr id="my" style="display: block;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
<?php if ($row8[0]=='HIGH')
{$statuscss= 'taskHigh';}
elseif ($row8[0]== 'MEDIUM')
{$statuscss= 'taskMedium ';}
else{ $statuscss= 'taskLow';}
echo 'class="',$statuscss,'"';?> style="margin-left: 30px;">OD_<?php echo $task1234?></p></td></tr>
<?php }?>
</tbody>
</table>
<table border='0' style="float:left; width:20%; height: 500px; border-radius: 5px; display: block;" bgcolor="#2B4353">
<thead>
<tr>
<td bgcolor="#2B4353" border="0" valign="top" align="right">
<div class="messages-header-team" onclick="teamTasks()"><p id="teamTasks">TEAM TASKS</p></div></td>
</tr>
</thead>
<tbody>
<?php
while($row8 = mysqli_fetch_array($TableTeam)){ $task1234=$row8[1];
?>
<tr id="team" style="display:none;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
<?php if ($row8[0]=='HIGH')
{$statuscss= 'taskHigh';}
elseif ($row8[0]== 'MEDIUM')
{$statuscss= 'taskMedium ';}
else{ $statuscss= 'taskLow';}
echo 'class="',$statuscss,'"';?> style="margin-left: 30px;">OD_<?php echo $task1234?></p></td></tr>
<?php }?>
</tbody>
</table>
My php
require('server.php');
session_start();
$email=$_SESSION['email'];
$sqli="Select URLDomain from Admin.Users where Email = ?";
$stmt =mysqli_prepare($link,$sqli);
mysqli_stmt_bind_param($stmt,"s",$email );
mysqli_stmt_execute($stmt);
$useremail=mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($useremail);
$DBdomain=$row[0];
mysqli_select_db($link,"Universe");
$stmt = mysqli_prepare($link,"Select Priority,TaskNumber from Task where urlDomain=?");
mysqli_stmt_bind_param($stmt,"s",$DBdomain );
mysqli_stmt_execute($stmt);
$TableTeam=mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
mysqli_select_db($link,"Universe");
$stmt = mysqli_prepare($link,"Select Priority,TaskNumber from Task where TaskOwner=?");
mysqli_stmt_bind_param($stmt,"s",$email );
mysqli_stmt_execute($stmt);
$TableMY=mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
Here is my Javascript
<script>
function messagesTab() {
document.getElementById("task-message").style.display = "block";
}
</script>
<script>
function myTasks() {
document.getElementById("myTasks").style.color = "#1FAC96";
document.getElementById("teamTasks").style.color = "#FFFFFF";
document.getElementById("team").style.display = "none";
document.getElementById("my").style.display = "block";
document.getElementById("messageDisplay").style.display = "block";
document.getElementById("myTaskView").style.display = "none";
}
</script>
<script>
function teamTasks() {
document.getElementById("teamTasks").style.color = "#1FAC96";
document.getElementById("teamTasks").style.underline = "#1FAC96";
document.getElementById("myTasks").style.color = "#FFFFFF";
document.getElementById("team").style.display = "block";
document.getElementById("my").style.display = "none";
document.getElementById("myTaskView").style.display = "none";
document.getElementById("messageDisplay").style.display = "block";
}
</script>
<script>
function myTaskView(Task_Number) {
$.ajax({
url:'messages_select.php',
type:'POST',
data:{Task_Number:Task_Number},
success:function(data){
$('#myTaskView').html(data);
document.getElementById("myTaskView").style.display = 'block';
document.getElementById("messageDisplay").style.display = 'none';
}
});
}
</script>
<script>
var main = function() {
$('form').submit(function(event) {
var $input = $(event.target).find('input');
var comment = $input.val();
if (comment != "") {
var user = '<i class="fas fa-user-circle"></i>';
var userInfo = $(user).text(' '+'nataliekoly#mail.usf.edu'+' | '+'01/31/19'+' | '+'3:45 PM')
var comment = $('<li>').text(comment);
comment.prependTo('#comments');
userInfo.prependTo('#comments');
$input.val("");
}
return false;
});
}
$(document).ready(main);
</script>
IDs need to be unique, you can't have id="my" and id="team" on each row of the table. Use classes instead:
<tr class="my" style="display: block;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
and
<tr class="team" style="display:none;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
Then you need to loop over them:
document.querySelectorAll(".my").forEach(el => el.style.display = "block");

how to redirect page in CI controler using HMVC method on jquery mobile

I am currently building eCommerce site using CI HMVC method. I completed it for computer design and all back-end. It work perfectly. But my dessign is terrible for mobile so i decided to write jquery mobile code. I almost complete the code in jquery mobile but i got i problem which i cannot solve.
I have the form which is use to add the item into the cart. For this i have add to cart function which has view file add_to_Cart.php whis has actual form. After submitting form goes to store_basket/add_to_basket function. Here i writ code to sore the comming information to store_basket table. Then it redirect the page to another controller cart where i have view file of list of items which is in cart.
when i submit the form it store item in store_basketm table. Then it show the view of cart controller but the url is localhost/shop/store_basket/add_to_basket Which should be localhost/shop/cart. But despite of url localhost/shop/store_basket/add_to_basket it show the contents of localhost/shop/cart
<?php $form_location = base_url().'store_basket/add_to_basket'; ?>
<div id="cart" style="background-color: #ddd; border-spacing: 7px; padding: 7px; color: black;">
<form ajax-date="false" data-url="true" action="<?= $form_location ?>" method="POST">
<table class="table">
<tr>
<td>ID: </td>
<td><?php echo $item_id ?></td>
</tr>
<input type="hidden" name="item_id" value="<?php echo $item_id ?>">
<input type="hidden" name="item_title" value="<?php echo $item_title ?>">
<?php if($num_colour > 0): ?>
<tr>
<td style="padding-top: 20px;">Colour: </td>
<td style="margin-left: 50px;">
<?php
$status = '';
$additional_dd_code = 'name="select-choice-mini" id="select-choice-mini" data-mini="true" data-inline="true"';
echo form_dropdown('item_colour', $colour_options, $submitted_colour, $additional_dd_code);
?>
</td>
</tr>
<?php endif; ?>
<?php if($num_size > 0): ?>
<tr>
<td style="padding-top: 20px;">Size: </td>
<td style="margin-left: 50px;">
<?php
$status = '';
$additional_dd_code = 'name="select-choice-mini" id="select-choice-mini" data-mini="true" data-inline="true" style="background-color: white;"';
echo form_dropdown('item_size', $size_options, $submitted_size, $additional_dd_code);
?>
</td>
</tr>
<?php endif; ?>
<tr>
<td>Price: </td>
<td><?= $item_price ?></td>
</tr>
<input type="hidden" name="price" value="<?= $item_price ?>">
<tr>
<td style="padding-top: 20px;">Qty: </td>
<td>
<input type="number" name="item_qty" value="1" min="1" required>
</td>
</tr>
</table>
<!-- <a rel="external" href=""><input name="submit" value="Submit" class="btn"></a> -->
<button type="submit" name="submit" value="Submit" id="cart-btn" class="ui-shadow ui-btn ui-corner-all" style="margin-top: 20px; width: 75%; margin-left: 30px;"><span class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> Add To Basket</button>
<?php echo form_close() ?>
store_basket/add_to_basket
function add_to_basket() {
// var_dump($_POST); exit;
$this->load->module('site_settings');
$this->load->library('session');
$this->load->module('site_security');
$is_mobile = $this->site_settings->is_mobile_device();
$submit = $this->input->post('submit', TRUE);
if($submit == "Submit"){
//library for form validation
$this->load->library('form_validation');
//validation rules
$this->form_validation->set_rules('item_colour', 'Item Color', 'numeric');
$this->form_validation->set_rules('item_size', 'Item Size', 'numeric');
$this->form_validation->set_rules('item_qty', 'quantity', 'required|numeric');
$this->form_validation->set_rules('item_id', 'Item_id', 'required|numeric');
if($this->form_validation->run($this)) {
// echo "Success"; exit;
$data = $this->_fetch_the_data();
$this->_insert($data);
redirect('cart');
} else {
// echo "Fail"; exit;
$refer_url = $_SERVER['HTTP_REFERER'];
$error_msg = validation_errors("<p style='color: red;'>","</p>");
$this->session->set_flashdata('item', $error_msg);
redirect('cart');
}
}
}
cart/index.php
function index() {
// echo "here"; exit;
$this->load->module('site_settings');
$is_mobile = $this->site_settings->is_mobile_device();
$data['flash'] = $this->session->flashdata('item');
$data['view_files'] = "cart";
if($is_mobile==TRUE) {
$data['view_files'] .= "_jqm";
$template = 'public_jqm';
} else {
$template = 'public_boostrap';
}
$token = $this->uri->segment(3);
if($token!='') {
$session_id = $this->_check_and_get_session_id($token);
} else {
$session_id = $this->session->session_id;
}
$this->load->module('site_security');
$shopper_id = $this->site_security->_get_user_id();
if(!is_numeric($shopper_id)) {
$shopper_id = 0;
}
$table = 'store_basket';
$data['query'] = $this->_fetch_cart_contents($session_id, $shopper_id, $table);
//count the items in basket or cart
$data['num_rows'] = $data['query']->num_rows();
$data['showing_statement'] = $this->_get_showing_statement($data['num_rows']);
$this->load->module('templates');
$this->templates->$template($data);
}

I am getting an "Undefined variable" error in CodeIgniter when fetching from database

I am getting error in codeigniter while fetching from the database.
Here is my error:
A PHP Error was encountered
Message: Undefined variable: results
Line Number: 122
Here is my code:
<?php $via = $this->session->userdata('firm_name');
if(!isset($firm_name)){ redirect ('Welcome');}
?>
<link href="<?php echo base_url("assets/css/radiostyle.css"); ?>" rel="stylesheet">
<style type="text/css">
.page-heading {
border-top: 0;
padding: 0px 10px 10px 10px;
}
input, button, select, textarea{
margin: 10px;
}
.ibox-content {
background-color: #ffffff;
color: inherit;
padding: 15px 20px 20px 20px;
border-color: #e7eaec;
border-image: none;
border-style: none;
border-width: 1px 0px;
}
</style>
<div class="row wrapper border-bottom white-bg page-heading">
<div style="float: left;" class="col-lg-4">
<img style=" width: 90px;
height: 90px; padding-top: 5px;" src="http://www.miisky.com/ci/GST.png" alt="GST Logo">
</div>
<div class="col-lg-4 text-center">
<h1 style=" padding-top: 7px;
padding-right: 20%;">Know Your Customers</h1>
</div>
<div style="float: right;" class="col-lg-4">
<h1 style="padding-top:9px"><?php echo "Date: ". date("d/m/Y");?></h1>
</div>
</div>
<br><div style="text-align: center;">
<label class="control control--radio">Manufacture
<input type="radio" onclick="document.location='#';" name="radio" checked="checked"/>
<div class="control__indicator"></div>
</label>
<label class="control control--radio">Service
<input type="radio" onclick="document.location='#';" name="radio" />
<div class="control__indicator"></div>
</label>
<label class="control control--radio">Trading
<input type="radio" onclick="document.location='#';" name="radio" />
<div class="control__indicator"></div>
</label>
<label class="control control--radio">Others
<input type="radio" onclick="document.location='#';" name="radio" />
<div class="control__indicator"></div>
</label>
</div>
<div class="fh-breadcrumb">
<div class="full-height">
<div class="full-height-scroll white-bg border-left">
<?php echo $this->session->flashdata('msg'); ?>
<div class="element-detail-box">
<div class="tab-content">
<div class="ibox-content">
<div class="form-group">
<div class="col-lg-12">
<div class="row">
<?php $this->load->helper('form'); ?>
<?php $attributes = array("name" => "Categoryform","autocomplete"=>"off");
echo form_open("Gst_customer/customersearch/", $attributes);?>
<div class="col-lg-6">
<input name="CustomerName" type="text" placeholder="CustomerName" value="<?php echo set_value('CustomerName'); ?>" class="form-control" required>
<span class="text-danger"><?php echo form_error('CustomerName'); ?></span>
</div>
<div class="col-lg-12">
<?php echo form_submit('Search', 'Search','class="btn btn-info"'); ?>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="full-height">
<div class="full-height-scroll white-bg border-left">
<?php echo $this->session->flashdata('message'); ?>
<div class="element-detail-box">
<div class="table-responsive">
<?php if(isset($results)){ ?>
<table class='table table-bordered'>
<thead>
<tr>
<th> Customer Name </th>
<th> Customer Id</th>
<th> Customer Code</th>
</tr>
</thead>
<tbody>
<?php foreach($results as $row){ ?>
<tr>
<td><?php echo $row->CustomerName;?></td>
<td><?php echo $row->CustomerID;?></td>
<td><?php echo $row->CustomerCode;?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
This is my controller file:
<?php
class Gst_customer extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('url','html'));
$this->load->library('session');
$this->load->database();
$this->load->model('user_model');
}
function index()
{
$details = $this->user_model->get_user_by_id($this->session->userdata('id'));
$data['firm_name'] = $details[0]->firm_name;
$data['email'] = $details[0]->email;
$data['vault_no'] = $details[0]->vault_no;
$data['active'] = 'know_your_customer';
$data['mobile'] = $details[0]->mobile;
$this->load->view('view_header', $data);
$this->load->view('view_menu', $data);
$this->load->view('gst_customer_view', $data);
$this->load->view('view_footer');
}
function customersearch()
{
$CustomerName = $this->input->post('CustomerName');
$data['results'] = $this->user_model->search($CustomerName);
$results = $data['results'];
$this->load->view('view_header', $data);
$this->load->view('view_menu', $data);
$this->load->view('gst_customer_view', $data);
$this->load->view('view_footer');
}
function logout()
{
$user_data = $this->user_model->get_user_by_id($this->session->userdata('id'));
foreach ($user_data as $key => $value) {
if ($key != 'session_id' && $key != 'ip_address' && $key != 'user_agent' && $key != 'last_activity') {
$this->session->unset_userdata($key);
}
}
$this->session->sess_destroy();
redirect('Welcome', 'refresh');
}
}
This is my model:
module.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function search($CustomerName,$CustomerID)
{
$this->db->like('CustomerName',$CustomerName);
$this->db->like('CustomerID',$CustomerID);
$query = $this->db->get('gst_customermaster');
return $query->result();
}
}?>
In your view.Show table if $results array is set.Because your are sending different data from different function to same view.
Like this..
<?php if(isset($results)){ ?>
<table class='table table-bordered'>
<thead>
<tr>
<th> Customer Name </th>
<th> Customer Id</th>
<th> Customer Code</th>
</tr>
</thead>
<tbody>
<?php foreach($results as $row){ ?>
<tr>
<td><?php echo $row->CustomerName;?></td>
<td><?php echo $row->CustomerID;?></td>
<td><?php echo $row->CustomerCode;?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
To get all data in index. Try this:
module.php
class User_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function search($CustomerName)
{
$this->db->like('CustomerName',$CustomerName);
$query = $this->db->get('gst_customermaster');
return $query->result();
}
function getAll()
{
$query = $this->db->get('gst_customermaster');
return $query->result();
}
}?>`enter code here`
controller file:
<?php
class Gst_customer extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('url','html'));
$this->load->library('session');
$this->load->database();
$this->load->model('user_model');
}
function index()
{
$details = $this->user_model->get_user_by_id($this->session->userdata('id'));
$data['firm_name'] = $details[0]->firm_name;
$data['email'] = $details[0]->email;
$data['vault_no'] = $details[0]->vault_no;
$data['active'] = 'know_your_customer';
$data['mobile'] = $details[0]->mobile;
//$data['results'] = $this->user_model->getAll();
$data['results'] = array();
$this->load->view('view_header', $data);
$this->load->view('view_menu', $data);
$this->load->view('gst_customer_view', $data);
$this->load->view('view_footer');
}
function customersearch()
{
$results = $this->user_model->get_user_by_id($this->session->userdata('id'));
$data['firm_name'] = $results[0]->firm_name;
$id = $this->input->post('id');
$data['results']=array();
$CustomerName = $this->input->post('CustomerName');
if(trim($CustomerName) != "")
{
$data['results'] = $this->user_model->search($CustomerName);
}
$results = $data['results'];
$this->load->view('view_header', $data);
$this->load->view('view_menu', $data);
$this->load->view('gst_customer_view', $data);
$this->load->view('view_footer');
}
function logout()
{
$user_data = $this->user_model->get_user_by_id($this->session->userdata('id'));
foreach ($user_data as $key => $value) {
if ($key != 'session_id' && $key != 'ip_address' && $key != 'user_agent' && $key != 'last_activity') {
$this->session->unset_userdata($key);
}
}
$this->session->sess_destroy();
redirect('Welcome', 'refresh');
}
}

Editing MySQL row via POST form

I've encountered a problem which i'll try to describe below...
Let's say i've got a button for each table row (table is created by acquiring the data from the database...). the button sends a massive of values via post.
<button value='$e->eventId|$e->eventType|$e->eventDate|$e->eventPrice|$e->eventDescr' name='editValue'>EDIT</button>
I've written a function to explode the values of the massive and fill the inputs on the same page.
if(!empty($_POST['editValue'])) {
$editValue_fill = explode("|", $_POST["editValue"]);
$eventId = $editValue_fill[0];
$eventType = $editValue_fill[1];
$eventDate = $editValue_fill[2];
$eventPrice = $editValue_fill[3];
$eventDescr = $editValue_fill[4];
}
Next comes the function to edit the row in the database.
function editEvent ($id, $type, $date, $price, $descr){
$mysqli = new mysqli($GLOBALS["serverHost"], $GLOBALS["serverUsername"], $GLOBALS['serverPassword'], $GLOBALS['dbName']);
$stmt = $mysqli->prepare("UPDATE events_archive SET eventType='?', eventDate='?', eventPrice='?', eventDescr='?' WHERE id='?'");
$stmt->bind_param("ssdss", $type, $date, $price, $descr, $id);
$stmt->execute();
header("Refresh:0");
if($stmt->execute()){
$eventNotice="Event successfully updated!";
}else{
$eventNotice = "Failed to save...";
}
return $eventNotice;
}
And, of course, the usage of the function which apparently doesnt work. The page just refreshes and nothing happens.
if(empty($eventTypeError)&& empty($eventDateError)&& empty($eventPriceError) && empty($eventDescrError)
&& isset($_POST['eventType']) && isset($_POST['eventDate']) && isset ($_POST['eventPrice']) && isset
($_POST['eventDescr']) && !empty($eventId)){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}
So basically, gets values from the row -> fills them into inputs in the same page -> if $eventId is set then updates the row, if not - creates a new row (diff. function)
Could anyone give me a tip or help solving the problem? I've been trying to understand the issue and failed dramatically...
<?php
require ("functions.php");
var_dump($_POST);
//kas on sisseloginud, kui ei ole siis
//suunata login lehele
//kas ?logout on aadressireal
if (isset($_GET['logout'])){
session_destroy();
header("Location: login.php");
}
if (!isset ($_SESSION["userId"])){
header("Location: login.php");
}
$confirm = "";
$eventNotice = "";
$eventTypeError = "";
$eventDateError = '';
$eventPriceError = '';
$eventDescrError = '';
$eventType = '';
$eventDescr = '';
$eventPrice = '';
$eventDate = date("Y-m-d");
if (isset ($_POST["eventType"])){
if (empty($_POST['eventType'])){
$eventTypeError = "Please choose the event type!";
} else {
$eventType = $_POST["eventType"];
}
}
if (isset ($_POST ["eventDate"])){
if (empty ($_POST ["eventDate"])){
$eventDateError = "Please choose the date!";
} else {
$eventDate = $_POST["eventDate"];
}
}
if (isset ($_POST ["eventPrice"])){
if (empty ($_POST ["eventPrice"])){
$eventPriceError = "Please type in the price!";
} else {
$eventPrice = $_POST["eventPrice"];
}
}
if (isset ($_POST ["eventDescr"])){
if (empty ($_POST ["eventDescr"])){
$eventDescrError = "Please type in the description!";
}elseif (strlen($_POST["eventDescr"])< 10) {
$eventDescrError = "Description must be longer than 10 symbols!";
$eventDescr = $_POST['eventDescr'];
}else{
$eventDescr = $_POST['eventDescr'];
}
}
$event = getAllEvents();
if(!empty($_POST['delValue'])) {
delEvent($_POST['delValue']);
}
if(!empty($_POST['editValue'])) {
$editValue_fill = explode("|", $_POST["editValue"]);
$eventId = $editValue_fill[0];
$eventType = $editValue_fill[1];
$eventDate = $editValue_fill[2];
$eventPrice = $editValue_fill[3];
$eventDescr = $editValue_fill[4];
echo ($eventId);
echo ($eventDate);
echo ($eventPrice);
echo ($eventType);
echo ($eventDescr);
}
if(empty($eventTypeError)&& empty($eventDateError)&& empty($eventPriceError) && empty($eventDescrError)
&& isset($_POST['eventType']) && isset($_POST['eventDate']) && isset ($_POST['eventPrice']) && isset
($_POST['eventDescr'])){
if(isset($_POST['editValue'])){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}elseif(!isset($_POST['editValue'])){
$eventNotice = newEvent(cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}
}
?>
<html>
<style>
#import "styles.css";
ul.tab {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
ul.tab li {float: left;}
ul.tab li a {
display: inline-block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
transition: 0.3s;
font-size: 17px;
}
ul.tab li a:hover {
background-color: #ddd;
}
ul.tab li a:focus, .active {
background-color: #ccc;
}
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
</style>
<body>
<form method ="post">
<table class="table1">
<tr>
<td style="text-align:center"><h1>Data</h1></td>
</tr>
<tr>
<th><h2>Profile</h2></th>
</tr>
<tr>
<td>
<table class="table2">
<tr>
<td colspan="3"">Welcome <?=$_SESSION['email'];?>!</td>
</tr>
<tr>
<td colspan="3" style="text-align:center">Log out</td>
</tr>
</table>
<tr>
<td>
<tr>
<td>
<ul class="tab">
<li>Add/edit</li>
<li>Archive</li>
</ul>
<div id="Add/edit" class="tabcontent">
<input type="hidden" value='eventId'>
<table class="table2">
<tr>
<td>Event type:<span class = 'redtext'>*</span></td>
<td style="text-align:left">
<select name="eventType">
<?php if(empty($eventType)){?>
<option value="" selected>Choose here</option>
<?php } else { ?>
<option value="">Choose here</option>
<?php } ?>
<?php if($eventType == "Planned service"){?>
<option value="Planned service" selected>Planned service</option>
<?php } else { ?>
<option value="Planned service">Planned service</option>
<?php } ?>
<?php if($eventType == "Unplanned service"){?>
<option value="Unplanned service" selected>Unplanned service</option>
<?php } else { ?>
<option value="Unplanned service">Unplanned service</option>
<?php } ?>
<?php if($eventType == "Fuel checks"){?>
<option value="Fuel checks" selected>Fuel checks</option>
<?php } else { ?>
<option value="Fuel checks">Fuel checks</option>
<?php } ?>
<?php if($eventType == "Tuning"){?>
<option value="Tuning" selected>Tuning</option>
<?php } else { ?>
<option value="Tuning">Tuning</option>
<?php } ?>
<?php if($eventType == "Car accident"){?>
<option value="Car accident" selected>Car accident</option>
<?php } else { ?>
<option value="Car accident">Car accident</option>
<?php } ?>
</select>
</td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventTypeError?></td></tr>
<tr>
<td>Date:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><input name="eventDate" type ="date" min="1900-01-01" max = "<?=date('Y-m-d'); ?>" value = "<?=$eventDate?>" placeholder="YYYY-MM-DD"></td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventDateError?></td></tr>
<tr>
<td>Price:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><input type="text" name="eventPrice" placeholder="ex. 15.50" onkeypress="return onlyNumbersWithDot(event);" / value = "<?=$eventPrice?>"></td>
<script type="text/javascript">
function onlyNumbersWithDot(e) {
var charCode;
if (e.keyCode > 0) {
charCode = e.which || e.keyCode;
}
else if (typeof (e.charCode) != "undefined") {
charCode = e.which || e.keyCode;
}
if (charCode == 46)
return true
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventPriceError?></td></tr>
<tr>
<td>Description:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><textarea name="eventDescr" cols="50" rows="10" placeholder="Describe event here..."><?=$eventDescr?></textarea></td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventDescrError?></td></tr>
<tr>
<td colspan="3" style="text-align:center"><button type ="submit" value = "Submit">Save</button></td>
</tr>
<tr>
<td colspan="3" style="text-align:center"><p class = "redtext"><?=$eventNotice;?></p></td>
</tr>
</table>
</div>
</form>
<form method="post">
<div id="Archive" class="tabcontent">
<table class="table2">
<tr>
<td colspan="3"">
<?php
$html = "<table>";
$html .= "<tr>";
$html .= "<th>Event type</th>";
$html .= "<th>Date</th>";
$html .= "<th>Price(€)</th>";
$html .= "<th>Description</th>";
$html .= "<th>Delete</th>";
$html .= "<th>Edit</th>";
$html .= "</tr>";
foreach($event as $e){
$html .= "<tr>";
$html .= "<td>$e->eventType</td>";
$html .= "<td>$e->eventDate</td>";
$html .= "<td>$e->eventPrice</td>";
$html .= "<td>$e->eventDescr</td>";
$html .= "<td><button style='border:none; background-color: transparent;' value='$e->eventId' name='delValue' onclick=\"return confirm('Do you really want to delete this row?')\"><img src='delete.png' width='20' height='20'></button></td>";
$html .= "<td><button style='border:none; background-color: transparent;' value='$e->eventId|$e->eventType|$e->eventDate|$e->eventPrice|$e->eventDescr' name='editValue'><img src='edit.png' width='20' height='20'></button></td>";
$html .= "</tr>";
}
$html .= "</table>";
echo $html;
?>
</td>
</tr>
</div>
<script>
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
</td>
</tr>
</table>
</td>
</tr>
</div>
</form>
</body>
</html>
Looking forward to Your help!
Best regards :)
if(isset($_POST['editValue'])){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}

In MVC, the update action doesn't work and stores the values

I took over a job from a friend. Now I am working on a MVC, I have made a Form that looks like his:
<form method="post" action="QA/public/index.php?controller=QA&action=shabUpdate">
<table class="clean">
{data}
<tr style="display:{display};">
<td class="label">Specific:</td>
<td>{remarks}</td>
</tr>
</table>
{back}
<input type="submit" />
</form>
In my controller I made the following shabUpdateAction:
protected function shabUpdateAction()
{
$_POST['titel'] = $_POST['titel'];
/*$_POST['inspectie'] = 'so sorry';
$_POST['extraDocument'] = 'newIMG';*/
$this->dbh->setShab($_POST, $_POST['partId']);
$_SESSION['page'] = './QA/public/index';
$_SESSION['getIndex'] = '?controller=QA&action=showInspectionDocument&templateId='.$_POST['templateId'];
header('Location: http://stuffff/something/');
exit();
}
this is suppose to update my form and when I visit the form page I should be able to see the new information (new changes that was made).
However the update action doesn't work and it doesn't redirect to a correct page.
this is the part from my Model:
public function updateSshab($sdr)
{
$sql = "UPDATE `qa_template`
SET `inspection_requirement` = :requirement
WHERE `part_id` = :partId AND `title` = :title;";
$statement = $this->dbh->prepare($sql);
$statement->bindParam(':requirement', $sdr['defectDescription']);
$statement->bindParam(':partId', $sdr['partId']);
$statement->bindValue(':title', 'SDR nummer: SDR' .$sdr['nr']);
$statement->execute();
}
and finally my view:
public function renderShowInspectionDocument()
{
setLastPage();
$dochtml = '';
$url = str_replace(end(explode('/', $_SERVER['HTTP_REFERER'])), '', $_SERVER['HTTP_REFERER']);
//Template
$template = file_get_contents('templates/inspectionDetails.tpl');
//shab
if(isset($this->data['shab']))
{
$shab= $this->data['shab'];
$dochtml .= '
<tr>
<td class="label">Inspection:</td>
<td>
<input type="hidden" name="templateId" value="'.$shab['id'].'" />
<div id="testDiv" style="width:420px; font-weight:normal; border-left:1px solid black; border-bottom:1px solid black; padding:5px;">'. nl2br($shab['inspection_requirement']) .'</div>
<div id="testDiv2" style="display=none">
<textarea name="inspection" class="width">'. nl2br($shab['inspection_requirement']) .'</textarea>
</div>
</td>
</tr>
<tr>
<td class="label">Inspection-tools:</td>
<td>
<input type="hidden" name="templateId" value="'.$shab['id'].'" />
<div id="testDiv22" style="width:420px; font-weight:normal; border-left:1px solid black; border-bottom:1px solid black; padding:5px;">'. nl2br($shab['inspection_resources']) .'</div>
<div id="testDiv222" style="display=none">
<textarea name="InspectieResources" class="width">'. nl2br($shab['inspection_resources']) .'</textarea>
</div>
</td>
</tr>
';
}
$template = str_replace('{data}', $dochtml, $template);
$template = str_replace('{terug}', backButtonQA(), $template);
$template = str_replace('{display}', 'none', $template);
echo $template;
}
my update function doesn't work correctly. I didn't write nu I am working on it and I cant seem to figure out the problem with update Action, is there something I am missing??

Categories