I am new in CodeIgniter. I am using CodeIgniter for my project. I have done inserting data in database and retrieving data from the database and now I'm trying to delete row from the table in the database but I'm unable to do it.
I have tried many other way to do it but still no luck. My code is given below.
controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class School extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper(array('url','language'));
$this->load->model('Main_model');
}
public function index()
{
if($this->input->post('submit'))
{
$data=array(
'name'=> $this->input->post('name'),
'email'=> $this->input->post('email'),
'phone'=> $this->input->post('phone'));
$insert=$this->Main_model->std($data);
}
$this->data["fetch_user"]=$this->Main_model->fetch_user();
$this->load->view('form',$this->data);
}
public function delete_data()
{
$id=$this->uri->segment(3);
$this->Main_model->delete_data($id);
redirect(base_url()."deleted");
}
public function deleted()
{
$this->index();
}
}
?>
model:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main_model extends CI_Model
{
public function std($data)
{
$insert=$this->db->insert('user',$data);
return $this->db->insert_id();
}
function fetch_user()
{
$this->db->select('*');
$this->db->from('user');
$query=$this->db->get();
return $query->result();
}
function delete_data($id)
{
$this->db->where("id",$id);
$this->db->delete("user");
}
}
?>
view:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<style>
input[type=text],input[type=number],input[type=email]
{
height:30px;
width:250px;
outline:none;
}
input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button
{
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
margin: 0;
}
td,th,h3
{
font-size:18px;
font-family:arial;
}
input[type="submit"]
{
padding:10px 20px;
border:none;
border-top-left-radius: 25px;
border-bottom-right-radius: 25px;
background:#7e57c2;
color:#ffffff;
outline:none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h3>School Student data</h3>
<form method="post">
<table cellspacing="5" cellpadding="5">
<tr>
<td>Name</td>
<td><input type="text" name="name" required></td>
</tr>
<tr>
<td>Phone No.</td>
<td><input type="number" name="phone" required></td>
</tr>
<tr>
<td>E-Mail</td>
<td><input type="email" name="email" required></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Insert"></td>
</tr>
</table>
</form>
<br><br>
<table border="1" cellspacing="5" cellpadding="5" >
<tr>
<th style="padding:10px 20px;">ID</th>
<th style="padding:10px 20px;">Name</th>
<th style="padding:10px 20px;">Email</th>
<th style="padding:10px 20px;">Phone No.</th>
<th style="padding:10px 20px;">Action</th>
</tr>
<?php
if($fetch_user !=null)
{
foreach($fetch_user as $row)
{
?>
<tr>
<td><?php echo $row->id;?></td>
<td><?php echo $row->name;?></td>
<td><?php echo $row->email;?></td>
<td><?php echo $row->phone;?></td>
<td>Delete</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td colspan="4">sorry no data found</td>
</tr>
<?php
}
?>
</table>
<script>
$(document).ready(function(){
$('.delete_data').click(function(){
var id=$(this).attr("id");
if(confirm("are you sure you want to delete this?"))
{
window.location="<?php echo base_url(); ?>delete_data/"+id;
}
else
{
return false;
}
});
});
</script>
</body>
</html>
Instead of using jQuery for this you could have directly set the anchor tag link :
<td>Delete</td>
This will directly send you to the function delete_data of the controller.
(instead of using class and click events in jquery)
Plus return yourself from the model to the controller on success.
function delete_data($id)
{
$this->db->where("id",$id);
$this->db->delete("user");
return;//onsuccess
}
Related
I have a dynamic form to add rows. The form lets the users to add transactions and submit it. I want to validate only the transaction numbers before inserting them into DB. I have to check
If the transaction field is empty or not
If the transaction already exists in the transactions table (if yes : display message transaction already exists. Please remove row. If no: proceed to DB insertion)
View part:
<div class="row">
<div class="col-md-12 ">
<?php echo validation_errors(); ?>
<?php
echo form_error("Transaction_number[]");
?>
<?php echo form_open('payment_refund/refund_form/'); ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<table id='tbl' class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Transaction_number</th>
<th>Order_number</th>
<th>Amount_paid</th>
<th>Transaction_date</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type='text' name='Transaction_number[]' value="<?php echo set_value('Transaction_number[]'); ?>" /></td>
<td><input type='text' name='Order_number[]' value="<?php echo set_value('Order_number[]'); ?>" /></td>
<td><input type='number' name='Amount_paid[]' value="<?php echo set_value('Amount_paid[]'); ?>" /></td>
<td><input type='date' name='Transaction_date[]' value="<?php echo set_value('Transaction_date[]'); ?>" /></td>
<td><input type='button' value='Remove' class='rmv'></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan='3'><input type='button' value='+Add Row' id='add_row'></td>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function(){
$("#add_row").click(function(){
var row="<tr> <td><input type='text' name='Transaction_number[]'></td> <td><input type='text' name='Order_number[]'></td> <td><input type='number' name='Amount_paid[]'></td> <td><input type='date' name='Transaction_date[]'></td> <td><input type='button' value='Remove' class='rmv'></td> </tr>";
$("#tbl tbody").append(row);
});
$("body").on("click",".rmv",function(){
$(this).closest("tr").remove();
});
});
</script>
<!-- Insert a check to see if any transaction details are entered before submit -->
<input type="submit" name="submit" id="submit" value="submit" class="btn btn-primary" >
<?php echo form_close(); ?>
</div>
Controller Part:
class Refund_form extends MY_Controller
{
public function __construct()
{
parent::__construct(array('stu'));
$this->load->model('payment_refund/refund_form_model','',TRUE);
}
public function index()
{
$this->load->helper('form');
$this->load->helper(array('form', 'url'));
$this->load->helper('array');
$this->load->library('form_validation');
$Transaction_number = $this->input->post('Transaction_number');
for($i = 0; $i < count($Transaction_number); $i++)
{
$tran = $Transaction_number[$i];
$this->load->library('form_validation');
$this->form_validation->set_rules($tran, 'Transaction', 'required');
}
if ($this->form_validation->run() == TRUE)
{
echo "All went well <br/>"; // insertion into DB for all table data fetched from view is done here
}
else
{
echo "All is NOT well <br/>";
}
public function add()
{
$this->drawHeader("Refund form - Add");
$this->load->view('payment_refund/refund_form_view');
$this->drawFooter();
}
Other methods that i tried to validate the form
`$formrules = array(
array(
'field' => 'Transaction_number[]',
'label' => 'the transsaction field',
'rules' => 'required'
),
);
$this->form_validation->set_rules($formrules);
if ($this->form_validation->run() == true)
{return true; } //DB insertion
else
{ return false; } `
DB insertion is done as below
for($i=0;$i<count($Transaction_number);$i++){
$data[] = [
'tracking_id' => $tracking_id,
'trans_id' => $Transaction_number[$i],
'order_id' => $Order_number[$i],
'amount' => $Amount_paid[$i],
'date_of_trans' => $Transaction_date[$i],
];
}
//inser_batch
$response=$this->db->insert_batch('refund_transaction_details',$data);
if($response==true){
echo "Records Saved Successfully";
}
else{
echo "Insert error !";
}
Hey I'm new to PHP and codeigniter. I have started with CRUD operation and I'm trying to insert data in my table. Everything seems to work fine but in my table the data is not inserted.
Here is my Model, Controller and View. Please elaborate my mistake in the code. What improvement my code needs.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class stdmain_controller extends CI_Controller
{
public function index()
{
echo "Hello";
}
public function insert_std_record()
{
$this->load->model('stdmain_model');
$this->load->view('std_insert_record');
}
Model
class Stdmain_model extends CI_Model
{
public function insert_std_record()
{
$data = array('std_name'=>$this->input->post('std_name'),'std_course'=>$this->input->post('std_course'),'std_mob'=>$this->input->post('std_mob') );
$this->db->insert('student_record',$data);
}
}
?>
View
<html>
<head>
<title>Insert Student Record</title>
</head>
<body>
<h1><center>Add Student Data</center></h1>
<form>
<table border="1">
<tr>
<th>Name</th>
<th><input type="text" name="std_name"></th>
</tr>
<tr>
<th>Couse</th>
<th><input type="text" name="std_course"></th>
</tr>
<tr>
<th>Mob No</th>
<th><input type="text" name="std_mob"></th>
</tr>
<tr>
<th>City</th>
<td colspan="2"><select>
<option value="Islamabad">Islamabad</option>
<option value="Lahore">Lahore</option>
</select>
</td>
</tr>
<tr>
<td colspan="2"><center><input type="submit"></center></td>
</tr>
</table>
</form>
</body>
</html>
Change your form tag like this
<form method="post" action="<?php echo base_url()?>index.php/stdmain_controller/insert_std_record">
Your form do not have any action.
Add this in you form opening tag:
<form method="post" action="<?php echo base_url("stdmain_controller/insert_std_record")?>">
I want to SAVE DATA into my sql using codeigniter, but when I click the
submit button,it shows error page cannot be found ....the view file shows but on click on submit button it shows error on next page.........
my view file
add.php
<html>
<head>
<title>Insert Employee Records in Database</title>
</head>
<body>
<form action="<?php echo base_url('emp_add/save'); ?>" method="post">
<table align="center">
<tr>
<td>First Name:</td>
<td><?php echo form_input(array('id'=>'fname', 'name'=>'fname',
'placeholder' => 'First Name', 'size'=>25));?></td>
</tr>
<tr>
<td>Last Name:</td>
<td><?php echo form_input(array('id'=>'lname', 'name'=>'lname',
'placeholder' => '
<tr>lname', 'size'=>25));?></td>
</tr>
<td>Email:</td>
<td><?php echo form_input(array('id'=>'email', 'name'=>'email',
'placeholder' => 'Email', 'size'=>25));?></td>
</tr>
<tr>
<td>Credits:</td>
<td><?php echo form_input(array('id'=>'credits',
'name'=>'credits',
'placeholder' => 'credits', 'size'=>25));?></td>
</tr>
<tr>
<td></td>
<td><button type="submit" id="submit" name="submit" >ADD</button>
</td>
</tr>
</table>
</form>
</body>
</html>
my controller file
emp_addd.php
<?php class Emp_add extends CI_Controller {
public function_construct() {
parent:: _construct();
$this->load->model('employee_model');
$this->load->helper(array('form','url'));
}
public function index()
{
$this->load->view('add'); }
public function save() {
$this->load->model('employee_model');
if($this->input->post('submit'))
{
$this->employee_model->process();
}
redirect('emp_add');
}
my model file
employee_model.php
<?php if (!defined('BASEPATH')) exit('No direct script access
allowed'); class Employee_model extends CI_Model {
public function process()
{
$save = array(
'fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname'),
'email' => $this->input->post('email'),
'credits' => $this->input->post('credits')
);
$this->db->insert('customers',$save);
}
} }
?>
SHOWING VIEW PAGE WELL. BUT ON SUBMIT IT SHOWS ERROR
Hi i have this delete thing, and im using it on ajax to delete the data. My problem is it wont delete on the database, when i refresh the browser the data remains, Can someone help me out figured this thing??
Here's my controller below
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start();
class News_and_events extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->model('admin_model', 'am');
}
public function index(){
if($this->session->userdata('logged_in')){
$this->data['title'] = 'News and Events | Spring Rain Global Consultancy Inc Admin Panel';
$this->data['logout'] = 'Logout';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->data['allData'] = $this->am->getAllData();
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/news_and_events', $this->data);
$this->load->view('pages/admin_footer');
}else{
redirect('login', 'refresh');
}
}
public function add(){
if($this->session->userdata('logged_in')){
$this->form_validation->set_rules('date', 'Date', 'trim|required|xss_clean');
$this->form_validation->set_rules('event', 'Event', 'trim|required|xss_clean');
$this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'News and Events | Spring Rain Global Consultancy Inc Admin Panel';
$this->data['logout'] = 'Logout';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->data['allData'] = $this->am->getAllData();
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/news_and_events', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'Date' => $this->input->post('date'),
'Event' => $this->input->post('event'),
'Description' => $this->input->post('description')
);
$this->am->saveData($array);
$this->session->set_flashdata('add_another',1);
redirect('news_and_events', 'refresh');
}
}else{
redirect('homepage', 'refresh');
}
}
public function delete(){
$id = $this->uri->segment(2);
$this->am->delete($id);
redirect(base_url().'news-and-events');
}
}
and my views
<script type="text/javascript">
$(document).ready(function(){
$("#add_another").click(function(){
});
});
function goDelete(id){
var agree = confirm("Are you sure you want to delete this?");
if(agree){
$("#news-and-event"+id).fadeOut('slow');
$.post('<?php echo base_url().'news-and-events/delete/'?>', {id:id}, function(){
});
}else{
return false;
}
}
</script>
<div class="container" >
<br />
<br />
<br />
<ul id="nav">
<li><h4>Home</h4></li>
<li><h4>News and Events</h4></li>
<li><h4>Activities</h4></li>
</ul>
<div class="starter-template">
<h1>News And Events</h1>
<?php if(!$this->session->flashdata('add_another')):?>
<form action="<?php echo base_url().'news-and-events/add'?>" method="post">
<?php echo validation_errors('<div class="error">', '</div>');?>
<table class="table-striped">
<tr>
<td>Date: </td>
<td><input type="text" id="datepicker" name="date" value="<?php echo set_value('date');?>" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td >Event: </td>
<td ><input type="text" name="event" value="<?php echo set_value('event');?>" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td width="20%">Description: </td>
<td><textarea cols="30" rows="5" name="description" ><?php echo set_value('description');?></textarea></td>
</tr>
<tr>
<td width="20%"> </td>
<td><input type="submit" value="Add" class="btn btn-success" /></td>
</tr>
</table>
</form>
<?php else: ?>
<div id="add_another" style="float:left;">
<input type="button" value="Add Another" class="btn btn-primary" />
</div>
<?php endif; ?>
<br />
<br />
<table class="table" >
<tr>
<th>Date</th>
<th width="47%" >Event</th>
<th width="32%">Description</th>
<th>Options</th>
</tr>
<?php foreach($allData as $x => $allDatas): ?>
<tr id="news-and-event<?php echo $allDatas->id; ?>">
<td width="10%"><?php echo $allDatas->Date; ?></td>
<td style="text-align:left;"><?php echo $allDatas->Event; ?></td>
<td style="text-align:left;"><?php echo $allDatas->Description; ?></td>
<td width="10%">
Edit |
<a href="javascript:;" onclick="return goDelete('<?php echo $allDatas->id;?>');" >Delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div><!-- /.container -->
<script>
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datepicker').datepicker({
minDate: new Date(currentYear, currentMonth, currentDate),
dateFormat: "yy-mm-dd"
});
</script>
and my model to delete the database
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Admin_model extends CI_Model{
public function saveData($array){
$this->db->insert('news_and_updates', $array);
}
public function getAllData(){
return $this->db->order_by("Date", "desc")
->get('news_and_updates')
->result_object();
}
public function delete($id){
$this->db->where('id', $id)->delete('news_and_updates');
}
}
?>
im using the $this->uri->segment(2); any help? is much greatly appreciated
thanks
You are sending data via POST but you are trying to delete based on the uri segment.
Try this instead in your controller:
public function delete(){
$id = $this->input->post('id');
$this->am->delete($id);
redirect(base_url().'news-and-events');
}
my code runs well but im getting this error Message: Undefined property: stdClass::$Date and i dont know where this error came from, as far as ive seen my codes are correct. The problem is in my foreach code
here's my controller below
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start();
class News_and_events extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->model('admin_model', 'am');
}
public function index(){
if($this->session->userdata('logged_in')){
$this->data['title'] = 'News and Events | Spring Rain Global Consultancy Inc Admin Panel';
$this->data['logout'] = 'Logout';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->data['allData'] = $this->am->getAllData();
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/news_and_events', $this->data);
$this->load->view('pages/admin_footer');
}else{
redirect('login', 'refresh');
}
}
}
my model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Admin_model extends CI_Model{
public function saveData($array){
$this->db->insert('news_and_updates', $array);
}
public function getAllData(){
return $this->db->select(
'news_and_updates.Event',
'news_and_updates.Description',
'news_and_updates.Date'
)
->from('news_and_updates')
->order_by("Date", "desc")
->get()->result_object();
}
}
?>
and my views
<script type="text/javascript">
$(document).ready(function(){
$("#add_another").click(function(){
alert('test');
});
});
</script>
<div class="container" >
<br />
<br />
<br />
<ul id="nav">
<li><h4>Home</h4></li>
<li><h4>News and Events</h4></li>
<li><h4>Activities</h4></li>
</ul>
<div class="starter-template">
<h1>News And Events</h1>
<?php if($this->session->flashdata('add_another')):?>
<div id="add_another" style="float:left;">
<input type="button" value="Add Another" class="btn btn-primary" />
</div>
<?php else: ?>
<form action="<?php echo base_url().'news-and-events/add'?>" method="post">
<?php echo validation_errors('<div class="error">', '</div>');?>
<table class="table-striped">
<tr>
<td>Date: </td>
<td><input type="text" id="datepicker" name="date" value="<?php echo set_value('date');?>" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td >Event: </td>
<td ><input type="text" name="event" value="<?php echo set_value('event');?>" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td width="20%">Description: </td>
<td><textarea cols="30" rows="5" name="description" ><?php echo set_value('description');?></textarea></td>
</tr>
<tr>
<td width="20%"> </td>
<td><input type="submit" value="Add" class="btn btn-success" /></td>
</tr>
</table>
</form>
<?php endif; ?>
<br />
<br />
<table class="table" >
<tr>
<th>Date</th>
<th width="51%">Event</th>
<th>Description</th>
<th>Options</th>
</tr>
<?php foreach($allData as $x => $allDatas): ?>
<tr>
<td><?php echo $allDatas->Date; ?></td>
<td><?php echo $allDatas->Event; ?></td>
<td></td>
<td></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div><!-- /.container -->
<script>
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datepicker').datepicker({
minDate: new Date(currentYear, currentMonth, currentDate),
dateFormat: "yy-mm-dd"
});
</script>
in my foreach code the error is this one $allDatas->Date; it says Message: Undefined property: stdClass::$Date
and that's the field name in my table Date
can someone help me figured this out??
any help is much appreciated! thanks! can't find the error
In your model or controller - after the getAllData method is executed:
echo the result of $this->db->last_query()
Manually execute the returned query in your database, then fix your query
As the comments started, The issue is that Date isn't generated from the query, which means something is wrong in that level, not the output itself.
Make sure the query is correct, dump it before you load the view directly from the controller to see what it gets, if it doesn't get a Date, your issue is elsewhere, probably in the query itself.