How to update and delete items from a sql database using codeigniter? - php

I wanted to be able to update and delete items for a list of products from an sql database. I already have the table from a database listed and I am able to read and insert a new product but I'm not sure how to update the product or delete it? Any advice or tutorials would be good? I have tried a few but none seem to work.
Here is my code for showing the products and inserting a new product
Product.php - controller
<?php
if (! defined('BASEPATH')) exit('No direct script access allowed');
class Product extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('product_model');
}
public function index()
{
$data['product_list'] = $this->product_model->getproduct();
$this->load->view('header');
$this->load->view('nav');
$this->load->view('product', $data);
$this->load->view('footer');
}
public function add_form()
{
$this->load->view('header');
$this->load->view('nav');
$this->load->view('insert');
$this->load->view('footer');
}
public function insert_product()
{
$pdata['Name'] = $this->input->post('Name');
$pdata['Type'] = $this->input->post('Type');
$pdata['Price'] = $this->input->post('Price');
$res = $this->product_model->insert_product($pdata);
if($res){
header('location:'.base_url()."index.php/Product/index");
}
}
}
?>
Product_model.php
<?php
class Product_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->database();
}
public function getproduct()
{
$query = $this->db->get('testProduct');
return $query->result();
}
public function insert_product($data)
{
return $this->db->insert('testProduct', $data);
}
}
?>
product.php - View
<h2> Product</h2>
<table width="600" border="1" cellpadding="5">
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">Type</th>
<th scope="col">Price</th>
</tr>
<?php foreach ($product_list as $p_key){ ?>
<tr>
<td><?php echo $p_key->id; ?></td>
<td><?php echo $p_key->Name; ?></td>
<td><?php echo $p_key->Type; ?></td>
<td><?php echo $p_key->Price; ?></td>
<td width="40" align="left" ><a href="#" <?php echo $p_key->id;?> >Edit</a></td>
<td width="40" align="left" ><a href="#" <?php echo $p_key->id;?>>Delete </a></td>
</tr>
<?php }?>
<tr>
<td colspan="7" align="right"> Insert New Product</td>
</tr>
</table>

What you are making is called CRUD - create, read, update, delete. There are a lot of examples of doing CRUD with CodeIgniter in Google.
Below are (over)simplified conceptual samples.
Based on your HTML, adding links to edit and delete a product:
<td width="40" align="left">
Edit
<!-- Don't really delete like this, seciruty issue! Just shown as a concept for manipulating records with IDs -->
Delete
</td>
And in Product.php - controller we'll add new methods to edit and delete
public function edit($id)
{
if($_SERVER['REQUEST_METHOD'] == "POST")
{
// get fields from form and update
// database record with them
$pdata['Name'] = $this->input->post('Name');
$pdata['Type'] = $this->input->post('Type');
$pdata['Price'] = $this->input->post('Price');
$this->product_model->update_product($id, $pdata);
}
else
{
// show form to edit product
// need to get product from database and pass to a view
$product = $this->product_model->getproduct_by_id($id);
$this->load->view('header');
$this->load->view('nav');
$this->load->view('edit', array("product" => $product));
$this->load->view('footer');
}
}
public function delete($id)
{
$this->product_model->delete($id);
}
edit.php - View
<form action="/index.php/product/edit/<?php echo $product->id ?>" method="post">
<table>
<tr>
<td><input name="name" value="<?php echo $product->Name; ?>"></td>
</tr>
<tr>
<td><input name="type" value="<?php echo $product->Type; ?>"></td>
</tr>
<tr>
<td><input name="price" value="<?php echo $product->Price; ?>"></td>
</tr>
<tr>
<td>
<input type="submit" value="Update">
</td>
</tr>
</table>
</form>
product_model.php
public function update_product($id, $pdata)
{
$this->db->where("product_id", $id);
$this->db->update("product", $pdata);
}

Related

Unable to update the selected boxes values in database using codeigniter php

Hi I am creating a view where I will be displaying the list of records from database along with boxes where a user selects checkboxes and click on Activate button. In the database I have given a separate column for featured blogs once user click on activate, these id columns should be updated as 1 and rest will be as 0.
View:
<table>
<thead>
<tr>
<th scope="col">Featured Blogs</th>
<th scope="col">S.No</th>
<th scope="col">Blog Title</th>
<th scope="col">Author</th>
</tr>
</thead>
<tbody>
<?php if(isset($records) && is_array($records) && count($records)>0): ?>
<?php $i=0;foreach($records as $r):$i++;?>
<tr>
<td><input type="checkbox" name="checkbox" value="<?php echo $r->blog_id;?>"
<?php if ($r->featured_blogs == 1) { echo 'checked="checked"'; }else { echo 'disabled="disabled"'; }?> ></td>
<td class="align-center"><?php echo $i;?></td>
<td><?php echo $r->blog_title;?></td>
<td><?php echo $r->username;?></td>
</tr>
<?php endforeach ;endif;?>
</tbody>
</table>
<div class="pagination"><?php echo $links; ?></div>
Activate
</div>
</div>
Controller:
function active()
{
$this->blogs_model->active($this->uri->segment(3));
$this->flash->success('<h2>Successfully Activated the record.<h2>');
redirect('blogs');
}
Model:
function activate($blog_id)
{
$data=array('status'=>1);
$this->db->where(array('blog_id'=>$blog_id));
$this->db->update('blogs',$data);
}
function active()
{
$this->blogs_model->active($this->uri->segment(3));
$this->flash->success('<h2>Successfully Activated the record.<h2>');
redirect('blogs');
}
function active($blog_id)
{
$data=array('status'=>1);
$this->db->where(array('blog_id'=>$blog_id));
$this->db->update('blogs',$data);
}
on your controller you called the model and it's function as active($this->uri->segment(3))
but in your model you called it as function activate($blog_id)
you should need to change it

Codeigniter PHP pulling records from mysql database table to display on page

So it appears I'm in need of some more assistance, I'm trying get records from my database to show on my view page as row descending down for each value but I am just getting HTTP 500 errors not sure where I have went wrong.
ci_users - database schema
id(PK, int, not null)
user_name(nchar255, not null)
user_email(nchar255, not null)
user_password(nchar255, not null)
user_displayname(nchar255, not null)
user_active(smallint, not null)
user_level(smallint, not null)
userlist_view
<table cellSpacing="0" cellPadding="4" width="100%" border="0">
<tr bgColor="#a5a6a9">
<td width="20%" align="left"><b>User ID</b></td>
<td width="20%" align="left"><b>Username</b></td>
<td width="20%" align="center"><b>Email Address</b></td>
<td width="20%" align="center"><b>Displayname</b></td>
<td width="20%" align="center"><b>User Level</b></td>
</tr>
<?php
foreach ($result as $result) ?>
<tr>
<td width="20%" align="left"><?php echo $result[0]->id; ?></td>
<td width="20%" align="left"><?php echo $result[0]->user_name; ?></td>
<td width="20%" align="left"><?php echo $result[0]->user_email; ?></td>
<td width="20%" align="left"><?php echo $result[0]->user_displayname; ?></td>
<td width="20%" align="left"><?php echo $result[0]->user_level; ?></td>
<?php endforeach; ?>
</table>
userlist controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class userlist extends CI_Controller {
public function __construct(){
parent::__construct();
}
function index()
{
$this->load->view('userlist_view');
}
function records()
{
$data = array();
$this->load->model('userlist_database');
$result = $this->userlist_database->getUsers();
$this->load->view('userlist_view', $result);
}
function logout()
{
$this->session->sess_destroy();
$this->index();
}
}
?>
userlist_database model
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class userlist_database extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database();
}
function getUsers() {
$this->db->select('id','user_name','user_email','user_displayname','user_level');
$this->db->from('ci_users');
$query = $this->db->get();
return $result = $query->result();
}
}
?>
Missing </tr> at the foreach loop and improved
In Model
function getUsers() {
$this->db->select('id','user_name','user_email','user_displayname','user_level');
$this->db->from('ci_users');
$query = $this->db->get();
return $result = $query->result_array();
}
In Controller
$data['result'] = $this->userlist_database->getUsers();
$this->load->view('userlist_view', $data);
In View
<?php
foreach ($result as $item)
{
?>
<tr>
<td width="20%" align="left"><?php echo $item['id']; ?></td>
<td width="20%" align="left"><?php echo $item['user_name']; ?></td>
<td width="20%" align="left"><?php echo $item['user_email']; ?></td>
<td width="20%" align="left"><?php echo $item['user_displayname']; ?></td>
<td width="20%" align="left"><?php echo $item['user_level']; ?></td>
</tr>
<?php } ?>

How to create URL link in search result using Codeigniter?

I have already created an search function in Codeigniter and its working properly. The search function shows exactly what I want but I want the result to be link to another page. I am new to Codeigniter. Can somebody please help me?
Here is my Model
public function search($searchterm)
{
$sql = "SELECT title as title, author as author
FROM `edubooks`
WHERE title LIKE '$searchterm' OR author LIKE '$searchterm'";
$q = $this->db->query($sql);
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
else
{
return 0;
}
}
/******************Handler for search******************/
public function searchterm_handler($searchterm)
{
if($searchterm)
{
$this->session->set_userdata('searchterm', $searchterm);
return $searchterm;
}
elseif($this->session->userdata('searchterm'))
{
$searchterm = $this->session->userdata('searchterm');
return $searchterm;
}
else
{
$searchterm ="";
return $searchterm;
}
}
Controller
public function search()
{
$searchterm = $this->search_model->searchterm_handler($this->input->get_post('searchterm', TRUE));
$data['results'] = $this->search_model->search($searchterm);
$data['searchterm'] = $searchterm;
$this->load->view('search',$data);
}
and my view
<h2>Library Search System</h2>
<div id="formborder">
<form action ="search" method="post" id="searchform" name="searchform">
<b> Name of book : </b><input type="text" name="searchterm" id="searchterm" value="<?=$searchterm?>" />
<input type="submit" value="search" id="submit" />
</form>
</div>
<div id="tablebody">
<table id="table" width="100%" = border>
<?php if($results == false):?>
<tr>
<td>No records found.</td>
</tr>
<?php else:?>
<tr>
<th>Title</th>
<th>Author</th>
</tr>
<?php foreach($results as $r):?>
<tr>
<td align="center"><?php echo ($r->title); ?></td>
<td align="center"><?php echo ($r->author); ?></td>
</tr>
<?php endforeach;?>
<?php endif;?>
</table>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
I just want the result to go another page.
if you want a link per each result to redirect you to another pge, you have to place that new page's URL in the href of your anchor tag, just like any
HTML link. I realize you have a table, what I would do is create another column with a "learn more" link.
So in your case, change this:
<?php foreach($results as $r):?>
<tr>
<td align="center"><?php echo ($r->title); ?></td>
<td align="center"><?php echo ($r->author); ?></td>
</tr>
<?php endforeach;?>
To this:
<?php foreach($results as $r):?>
<tr>
<td align="center"><?= $r->title; ?></td>
<td align="center"><= $r->author; ?></td>
<td align="center">Learn More</td>
</tr>
<?php endforeach;?>
the anchor now looks like this:
<?= base_url()?>controller_name/controller_method/$r->id
which you would want to change to the method name of your choice, perhaps something like this:
<?= base_url()?>books/about/$r->id
^ ^ ^
| | |
| | parameter
| method
controller
it will redirect to that specific controller method passing the id of your book as a parameter. your job now is to build that method so that you can retrieve that specific book by id and parse it to a view.

CodeIgniter loads data from the controller but not from the view

Here's the issue : CodeIgniter loads data from the controller but not from the view
When I go the the source of the page and click the form action link its load data in the source code but not in the html view.
--view
<table class="table hovered">
<thead>
<tr>
<th class="text-left">User ID</th>
<th class="text-left">Type</th>
<th class="text-left">Name</th>
<th class="text-left">Email</th>
<th class="text-left">Phone</th>
</tr>
</thead>
<tbody>
<?php echo form_open('admin/manage_customer') ?><!-- start of the form -->
<?php if(isset($records)) : foreach($records as $row) : ?>
<tr>
<td class="right"><?php echo $row->cus_id; ?></td>
<td class="right">Admin</td>
<td class="right"><?php echo $row->cus_name; ?></td>
<td class="right"><?php echo $row->cus_email; ?></td>
<td class="right"><?php echo $row->cus_phone; ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
<?php echo form_close(); ?><!-- END of the form -->
</tbody>
<tfoot></tfoot>
</table>
---controller
function inbox()
{
$data = array();
if($query = $this->mod_contactus->get_records())
{
$data['records'] = $query;
}
$this->load->view('admin/admin_messages',$data);
}
---Model
<?php
class Mod_contactus extends CI_Model //Users (model name) share all the class and functions CodeIgniter models have
{
function get_records()
{
$query = $this->db->get('tbl_contactus');
return $query->result();
}
function add_record($data)
{
$this->db->insert('tbl_contactus', $data);
return;
}
function update_record()
{
}
}
i would go with hussain in this. first check if the necessary data is returned by the model or not. Only then you should check the html structure. But even if there is a problem with structure, something should be displayed. So, check the flow of data to the view first.

Searching, $_POST variable

I have this code block in html for inputting the search.
<?php echo form_open('bookstore/_searchbook'); ?>
<table>
<tr>
<td>
<label for="searchid">Search:</label>
</td>
<td>
<input type="text" size="15" name="searchid" />
</td>
</tr>
<tr>
<td>
<label for="searchtype">Type:</label>
</td>
<td>
<select>
<option value="book_id">Id</option>
<option value="book_author">Author</option>
<option value="book_name">Title</option>
</select>
</td>
</tr>
<tr>
<input type="submit" value="Search" />
</tr>
</table>
<?php echo form_close(); ?>
And i have this on my controller,
public function booksearch()
{
if($_POST['submit'])
{
$col= $this->input->post('searchtype', TRUE);
$val= $this->input->post('searchval', TRUE);
$data['book'] = $this->books_model->showbook($col,$val);
$this->load->view('showbooks',$data);
}
}
and this would be my model
public function showbook($col, $searchid)
{
$this->db->select()->from('books')->where(array($col=>$searchid));
$query=$this->db->get();
return $query->first_row('array');
}
Further info on my view,
I have this to print the results of my search.
<table cellpadding='5'>
<th>Book ID</th>
<th>Title</th>
<th>Author</th>
<th>Released Year</th>
<th>ISBN</th>
<?php
if(isset($books)) : foreach($books as $book) :
?>
<tr>
<td><?php echo $book['book_id'] ?></td>
<td><?php echo $book['book_name'] ?></td>
<td><?php echo $book['book_author'] ?></td>
<td><?php echo $book['book_year'] ?></td>
<td><?php echo $book['book_isbn'] ?></td>
</tr>
<?php
endforeach;
?>
<?php
else :
?>
<h5>No records</h5>
<?php
endif;
?>
</table>
It returns nothing so all i see is no records. Someone direct me to the thing i did wrong.
Your form's action (view) is _searchbook while your controller function is booksearch
Your submit input needs a name attribute
in the controller function you have $data['book'] while in your view (in the foreach loop) you reference that variable as $books
Model: you need to select at least something; e.g. $this->db->select('*')->from('books')->where(array($col=>$searchid)); instead of $this->db->select()
Model: I think you need return $query->result_array(); instead of $query->first_row('array')
Because your submit button has not got any name attribute. Instead of if($_POST['submit']) write $this->input->post(null)
Try adding global $_POST; to the top of your function. In php all variables used(declaired) in a function will be private unless you tell it otherwise by adding it to the global statement in the function.
public function booksearch()
{
global $_POST;
if($_POST['submit'])
{
$col= $this->input->post('searchtype', TRUE);
$val= $this->input->post('searchval', TRUE);
return $data['book'] = $this->books_model->showbook($col,$val);
}
}

Categories