update table row and save in database in php codeigniter - php

I am making a table from a database and want to add an Edit/delete button to each row update or delete a specific row from the database. I have successfully added working "delete" button but I have no idea how could I update data in table <td> in view and send it to controller.
Here is my code:
view file
<table class="table table-striped">
<tr>
<td>name</td>
<td>age</td>
<td>gender</td>
<td>class</td>
<td>roll no.</td>
</tr>
<?php foreach($record as $r): ?>
<tr>
<td><?php echo $r->name; ?></td>
<td><?php echo $r->age; ?></td>
<td><?php echo $r->gender; ?></td>
<td><?php echo $r->class; ?></td>
<td><?php echo $r->roll no; ?></td>
<td><a href="" >Edit</a>
<a href="<?php echo base_url()."student/deleteRow" ?id="$r->name">"
onclick="return confirm
('Are you sure to Delete?')"><i class="icon-trash"></a></td>
</tr>
<?php endforeach; ?>
</table>
Controller Function
public function deleteRow(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$this->student_model->rowDelete($id);
redirect($_SERVER['HTTP_REFERER']);
}
}
I don't know how can I now insert an input field to update table row without effecting previous view. Any suggestion would be helpful.

To Edit the Studen data you need to pass an id or uniue column name to the data base to get that student data.
First Set the student id in <a href=""> tag.
<td><a href="<?= base_url('student/edit_student') ?>/$r->id" >Edit</a>
Then When you click on the edit it will take you to the controller. You can get the third url parameter direct in as show in the controler code:
You can also use get as shon
Your Controller should be:
public function edit_student($id){
$student_data = $this->student_model->get_student_data($id);
$this->load->view('your_view',['student_data'=>$student_data)]);
}
Here is you model which get the id form controllr and find the student data and passit to back to the controller:
Your Model should be:
public function get_student_data($id){
$this->db->select('*');
$this->db->from('your_table_name');
$this->db->where('id',$id);
$query = $this->db->get();
$student_data = $query->$row_array();
if(isset($student_data) && !empty($student_data)){
return student_data;
} else {
return FALSE;
}
}
Form controller you pass the data to the view.
On View Side:
<?php
// Just to ensure the data. Comment it after testing
echo "<pre>";
print_r($student_data);
echo "</pre>";
?>
<form action="<?= base_url('student/update_student') ?>/<?= $student_data['id'] ?>">
<input name="your_column_name" value="<?= $student_data['your_column_name'] ?>">
// Try to do the same for all you column.
<input type="submit" value="updata">
</form>
Here is the controller for update the data
public function update_student($id){
$student_data = $this->input->post();
$status = $this->student_model->update_student($id,$student_data);
if($status == TRUE){
$this->load->view('your_view');
// Your Success view
} else {
// Your view if fail to update
$this->load->view('your_view');
}
}
Here is the model for update the data
public function get_student_data($id,$student_data){
$this->db->where('id',$id);
$this->db->update('your_table_name',$student_data);
if($this->db->affected_rows() == 1){
return TRUE;
} else {
return FALSE;
}
}

Very similar to what you have done for delete. Something like this:
<td>
<a href="" >Edit/Delete</a>
<!-- This should be another method in Student controller -->
<i class="icon-trash"><!-- I changed order of edit and delete -->
</td>
I need to warn you for CSRF. If you don't implement better security here, anyone pointing to that link would be able to edit or delete data.
Check Security class in documentation and how to set hidden value so that way you would ensure that only one who has already requested that page was able to edit/delete rows.

<td><a href="<?php echo base_url();?>controller_name/function_name/<?php echo $edit_id;?>" >Edit</a></td>
another way
<td><a href="<?php echo base_url();?>controller_name/function_name?id=<?php echo $edit_id;?>" >Edit</a></td>
You can use any one according to your requirement.

Related

how to delete a row in database using codeigniter

hye, i'm trying to do 'delete function' for my modul. i've tried so many different ways for this. but it come out no result, some come with error.
this is my controller (named expert.php) :
public function remove() {
$siri = $this->uri->segment(3);
$this->Kepakaran_m->delete($siri);
$this->view();
}
siri is the a field name (column name) in my table. it it primary key.
this is my model (named Kepakaran_m.php):
function delete($siri) {
$this->dbsmk->where('siri', $siri);
$this->dbsmk->delete('kexpt003pakar');
if ($this->dbsmk->affected_rows() == 1) {
return TRUE;
}
return FALSE;
}
kexpt003pakar is the table name.
so my view is this (named kepakaran.php):
<tbody>
<?php if(empty($kepakaran)) { ?>
<tr>
<td colspan="8">Pengguna tidak mempunyai rekod kepakaran!</td>
</tr>
<?php } else {
$num = 0;
foreach ($kepakaran as $list_kepakaran) {
$num++;
?>
<tr>
<td><?php echo $num; ?></td>
<td><?php echo $list_kepakaran->kategori; ?></td>
<td><?php echo $list_kepakaran->bidang; ?></td>
<td><?php echo $list_kepakaran->spesifik; ?></td>
<!-- untuk keluarkan tahap -->
<td><?php
if($list_kepakaran->tahap=='1'){
echo "Sederhana";
}elseif ($list_kepakaran->tahap=='2') {
echo "Tinggi";
}elseif ($list_kepakaran->tahap=='3') {
echo "Sangat Tinggi";
}
?>
</td>
<!-- done untuk keluarkan tahap -->
<td><?php echo $list_kepakaran->biltahun; ?></td>
<td>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#tambahkepakaran"><i class="glyphicon glyphicon-pencil"></i></button>
<i class="glyphicon glyphicon-trash"></i>
</td>
</tr>
<?php }} ?>
</tbody>
so the delete button is in this area >>siri; ?>" type="button".....
i hope your answer will help me to discover this up. thank you :)
What's the error? I think you just need to modify your codes becomes:
<i class="glyphicon glyphicon-trash"></i>
Then it should be ok.
In order to use uri segment..do not forget to call url helper in autoload.php
english is not my native language.
For solve your problem, you can check a lot of things.
Did you forget to load model in your controller ?
Try to dump value of $siri in your remove function and show response on your network tab in chrome devTools for example.
If you don't call your controller, look at side of your href or open Application/config/routes.php for use routing and add this $route['expert/remove/(:num)']['GET'] = "expert/remove/$1";
If $siri is empty look at the side of $this->uri->segment(3);
Verify if you load correctly the helper.
For that, go to Application/config/autoload.php and see if url is in helper $autoload['helper'] = array('url','security','language', 'form', 'text');

Getting an info from the DB with Tables and Updating it

Hi guys im having a difficulty with this scenario:
I want to get the product information using modals, i got this following code:
//Model.php
public function getProduct($product_id){
$this->db->select('product_id,product_name,product_price,product_qty');
$this->db->from('tbl_products');
$this->db->where('product_id',$product_id);
$query = $this->db->get();
return $query->result();
}
//Controller.php
public function view_product(){
$product_id = $this->input->post('product_id');
$this->load->view('header');
$this->data["post"] = $this->Model->ProductList();
$this->load->view('product_page',$this->data);
$this->data["post"] = $this->Model->getProduct($product_id);
$this->load->view('modal/update_product',$this->data);
}
//update_product.php (modal) my View
lets just go straight into the form
<form action="" method="post">
<?php foreach($posts as $post){ ?>
<input type = "hidden" name = "product_id" value = "<?php echo $post->product_id;?>"/>
<input type = "text" name = "product_name" value = "<?php echo $post->product_name;?>"/>
<input type = "text" name = "product_price" value = "<?php echo $post->product_price;?>"/>
<input type = "text" name = "product_qty" value = "<?php echo $post->product_qty;?>"/>
<button type="submit">Update</button>
<?php } ?>
</form>
I got a table already: i can see all products, in my product_page.php
Here is the tables face looks like:
ID Name Price Quantity Option
1 Shoes 150.00 1 Update
2 Liquor 67.50 5 Update
3 Paint 1000.00 5 Update
Once I click the Update button, the update_product.php(a modal) will pop up and get the result of 1 of the product, if I press the first Update only the information for Shoes will be inside the modal, at first i tried it, I get all the information of all the products which makes my modal redundant and looping due to foreach, then I tried getting the information from the table ID itself, and no product pops out, how can I see only 1 product using modal? thank you very much maam and sirs. Please I really need youre help :(
Although I'm not really clear what you're asking, Here is an answer to you question. Your controller code doesn't seem to be making any sense.If you want to display all your products in on page and then you want to edit/update a product when clicked on corresponding update link, here is what you can do.
Use single controller method for list and update
//Controller.php
public function view_product(){
$product_id = (isset($this->input->post('product_id')) ? $this->input->post('product_id'): False ;
if($product_id == False){
$this->data["post"] = $this->Model->ProductList();
$this->load->view('product_page',$this->data);
} else{
$this->data["post"] = $this->Model->getProduct($product_id);
$this->load->view('modal/update_product',$this->data);
}
}
This is simple modification to your code to make it work correctly, but since this code cannot handle form submission of the update form (unless you're pointing update form to a different controller), you will have to add some other code to this controller and your code will get messy in no time. My personal suggestion to you is this,
Use different controllers for list view and update
//Controller.php
public function view_product(){
$this->data["post"] = $this->Model->ProductList();
$this->load->view('product_page',$this->data);
}
public function update_product($product_id){
if($this->input>post('submit')){ // 'submit'should be replaced with the name attribute of your submit button
//call your model and handle the update form submission here
}
$this->data["post"] = $this->Model->getProduct($product_id);
$this->load->view('product_page',$this->data);
}
now, update option of your product_page.php should point to 'update_product' controller method with corresponding product id e.g. {base_url}/controller_class_name/update_product/1
I think your product_page.php has some code like this to loop through all the products and display products in a table, now when you click update link it will point to update_product controller and it will handle the update process.
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Option</th>
</tr>
</thead>
<tbody>
<?php if(!$products){ ?>
<tr>
<td colspan="5">No result</td>
</tr>
<?php } ?>
<?php if($products){ ?>
<?php foreach ($products as $product) { ?>
<tr>
<td><?php echo $product->id; ?></td>
<td><?php echo $product->name; ?></td>
<td><?php echo $product->price; ?></td>
<td><?php echo $product->quantity; ?></td>
<td>
<a href="<?php echo base_url(); ?>controller_class_name/update_product/<?php echo $product->id; ?>" >Update</a>
</td>
</tr>
<?php } } ?>
</tbody>
</table>
You won't be needing a foreach loop inside your update_product.php because you're updating only one product at once.
Hope this is the answer you're looking for, if not please comment and I will edit the answer accordingly.

PHP foreach loop outside loop

I'm trying to wrap my head around PHP and variable scope. Take a look at the following:
<?php foreach ($data as $tip) { ?>
<tr>
<td><?php echo $tip['id']; ?></td>
<td><?php echo $tip['title']; ?></td>
<td class="delete"><i class="icon-cross"></i></td>
</tr>
<?php } ?>
This just runs a foreach loop that pulls some information out of the database and displays it in a table. The last table cell has an icon in it for deleting that article. What I'm trying to do is have a modal popup that asks for conformation to delete that specific article but I cannot tie the tip id with the delete button because the modal window sits outside the loop. How can I go about accessing the individual id?
Do this :
<?php foreach ($data as $tip) { ?>
<tr>
<td><?php echo $tip['id']; ?></td>
<td><?php echo $tip['title']; ?></td>
<td class="delete" onclick="deleteArticle(<?php echo $tip['id'] ?>)">
<a href="#deleteModal" class="modal">
<i class="icon-cross"></i>
</a>
</td>
</tr>
<?php } ?>
<script>
function deleteArticle(id){
// now you can do what ever you want to do with this id
}
</script>
There is a built it javascript function called "confirm".
If you're using JQuery (And I assume you are) try this:
$('.delete').click(function(){
var check = confirm("Are you sure you want to delete this article?");
if(check)
{
// you code here
}
else return false;
});

passing a php array item into a javascript popup window to be edited and updated in mysql db

I am creating a diabetes management system for a university project. One of the features of this system is for the patient to be able to send latest glucose readings and for the nurse to be able to login and comment on those readings.
I have been able to code the patient feature, however I wish to add a comment button in the comments column, which when clicked, brings up a popup window or a textbox for the nurse to be able to comment on that specific record. If a comment has not already been entered, an empty box should come up, however if there has been a previously entered comment, it should be displayed in the box to be updated and sent back to the mysql database. I would like to ask if someone could give me a way to include this comment box and code for the existing value to be displayed in the box and if there is no existing comment, then a new comment can be entered and stored in the database.
Below is my php code.
<?php//run query
$result = mysql_query($GetReadings);
?>
<table>
<tr>
<th>Date</th>
<th>Time</th>
<th>Glucose Level</th>
<th>SBP</th>
<th>DBP</th>
<th>Comments</th>
</tr>
<?php
//display results
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<tr>
<td><?php echo $row["Date"]; ?> </td>
<td><?php echo $row["Time"]; ?> </td>
<td><?php echo $row["GlucoseLevel"]; ?> </td>
<td><?php echo $row["SBP"]; ?> </td>
<td><?php echo $row["DBP"]; ?> </td>
<td><?php echo $row["Comments"];
<?php
//if statement to add comment link if user is a nurse
if ($_SESSION['User_level'] == 2)
{
//code for comments
}
?> </td>
</tr>
<?php
//end of while loop
}
?>
Hope I haven't missed out any crucial information.
Use the javascript function :
window.open(URL, windowName[, windowFeatures])
Where, URL - desired URL to display a page containing Textbox, use any window name you want.
Echo <a> or button with a onclick event eg:
Add Comment
Edit
The most basic way to achieve is, echo a <div></div> containing the past comments, the text box for new comments and Send/Cancel buttons. The trick is to set the display:none style property of that div. You the following code a guideline :
Echo the following code if the User has right user level.
Show Comments
<div id="comment-<?php echo $row['id']?>" style="display:none">
//display previous comments
<form method="post" action="addComment.php?id=<?php echo $row['id']?>">
<textarea name="comment"></textarea>
<input type="submit" value="Add Comment" /><input type="button" onclick="hideComment('<?php echo $row['id']?>')">
</form>
</div>
<script type="text/javascript">
function hideComment(id) {
document.getElementById('comment-' + id).style.display = 'none';
}
function showComment(id) {
document.getElementById('comment-' + id).style.display = 'block';
}
</script>

Link to a Controller function with parameter from a View (CodeIgniter)

Using CodeIgniter I am trying to create a link that the user can click within a view to show them the details of a record in my database.
In ASP.NET MVC3 with C# I would do it with #Html.ActionLink("Controller", "Action", new { id = item.Id})
This is my session controllers index() function
public function index()
{
$data['sessions'] = $this->session_model->get_sessions();
$this->load->view('_header');
$this->load->view('session/index', $data);
$this->load->view('_footer');
}
This is the index view it loads where I want to be able to click the link to go to enter() function
<table>
<th>Session Name</th>
<th>Description</th>
<th>Host</th>
<th></th>
<?php foreach ($sessions as $session_item): ?>
<tr>
<td> <?php echo $session_item['sessionName'] ?> </td>
<td> <?php echo $session_item['sessionDesc'] ?> </td>
<td> <?php echo $session_item['adminName'] ?> </td>
<td> <a id="enterSession" href=<?php echo site_url("session/enter" + $session_item['id']) ?> >Enter</a></td>
</tr>
<?php endforeach ?>
The enter session points me to the url "http://192.168.1.36/index.php/1" (if the id of my item is 1) whereas I expect "http://192.168.1.36/index.php/session/enter/1"
Any ideas on how I can make it call the enter() function also in the session controller (shown below)
public function enter($id) {
$this->load->view('_header');
$this->load->view('session/enter');
$this->load->view('_footer');
}
There seems to be a typo in the string concatenation in your PHP code. Perhaps it will work to use:
site_url("session/enter" . $session_item['id'])
... rather than a + sign between the two strings.
Regarding the second question - it looks correct as-is. Is it failing to call the session controller's enter() function passing the $id as an argument (assuming the URL is correct)?.

Categories