how to delete a row in database using codeigniter - php

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');

Related

"Issue with updating a record using a button”

When I click on the update button, the SQL query updates the last record not the wanted one
when displaying several courses, I would like to give the user the right to confirm one of the courses, when I click on the update button, it updates the last record
<?php
$cc = mysqli_query($mysqli, "SELECT * from course WHERE c_email ='$emailu' AND course_situation='pending'");
while($ccc = mysqli_fetch_array($cc)) {
$idcourse = $ccc['idcourse'];
$city = $ccc['idville'];
$pickup = $ccc['course_depart'];
?>
<tr>
<td><?= $idcourse ?></td>
<td><?= $pickup ?></td>
<td><?php echo $ccc['course_date'] ?>, <?php echo
$ccc['course_heure'] ?></td>
<td>
<?php
if($ccc['course_situation'] == "pending") { ?>
<span class="badge badge-danger">Pending</span>
<?php } else { ?>
<span class="badge badge-success">Confirmed</span>
<?php } ?>
</td>
<td><?php echo $ccc['c_phone'] ?></td>
<td><?php echo $ccc['c_phone'] ?></td>
<td><?php echo $ccc['idclient'] ?></td>
<td>
<button type="submit" name="cancelcourse" class="btn btn-danger btn-xs"><i class="icon md-check" aria-hidden="true"></i> Update</button>
</tr>
<?php }
if(isset($_POST["cancelcourse"])) {
$query = "UPDATE course SET id='$idu' AND course_situation='confirmed' WHERE idcourse='$idcourse' ";
if(mysqli_query($mysqli, $query)) {
echo "<div class=' alert alert-success' style='padding-left:150px'>
<strong>Success!</strong> Event page updated.</a>.
</div>";
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index.php">';
} else {
echo "<div class='alert alert-danger'>
<strong>ERROR!</strong> We invite you to try Again Later.
</div> " . mysqli_error($mysqli);
}
}
You generate button for each course, but all your buttons are equal, they don't contains any information about which course you want to update. You use variable $idcourse, but it is assigned inside while-loop that generates table - for each row that is shown this variable is changed, so after showing whole table it will contains id for last row.
Please remember, that each time your page is reloaded (like after clicking button) whole script is executed from beginning and no variables are stored, unless you pass it yourself.
Simplest solution:
1.Add id to button
<button type="submit" name="cancelcourse" class="btn btn-danger btn-xs" value="<?=htmlspecialchars($idcourse)?>">
2.Change query
$idcourseToRemove = mysqli_real_escape_string($mysqli, $_POST["cancelcourse"]);
$query = "UPDATE course SET id='$idu' AND course_situation='confirmed' WHERE idcourse='$idcourseToRemove' ";
And last advice: learn about SQL Injection and how to avoid it (like for example by mysqli_real_escape_string function)
UPDATE course SET id='$idu',course_situation='confirmed' WHERE
idcourse='$idcourse'

CodeIgniter: Including a php script inside the controller

I have a function inside my controller that outputs html elements to a view. This is how it looks like.
function show_res() {
$output = '';
foreach($data->result() as $row) {
if($row->user_agency == $user_agency) {
$output .= '
<tr>
<td>'.$row->user_name.' '.$row->user_lname.'</td>
<td>'.$row->user_type.'</td>
<td>
<button>Edit</button>
<button>Delete</button>
</td>
</tr>
';
}
}
echo $output;
}
My task is that I need to include a php function for when the delete button is clicked, so far this is what I've tried:
if($row->user_agency == $user_agency) {
$output .= '
<tr>
<td>'.$row->user_name.' '.$row->user_lname.'</td>
<td>'.$row->user_type.'</td>
<td>
<button>Edit</button>
<a href="<?php echo base_url().delete_c/delete_user/.$row->user_id; ?>">
<button>Delete</button>
</a>
</td>
</tr>
';
}
and
if($row->user_agency == $user_agency) {
$output .= '
<tr>
<td>'.$row->user_name.' '.$row->user_lname.'</td>
<td>'.$row->user_type.'</td>
<td>
<button>Edit</button>
<a href="'.echo base_url().'delete_c/delete_user/'.$row->user_id'">
<button>Delete</button>
</a>
</td>
</tr>
';
}
The problem with the first one is that the whole
<?php echo base_url().delete_c/delete_user/.$row->user_id; ?>
is added as a string instead of a php script so when I click on the button it would redirect to this URL
https://localhost/test/<?php%20echo%20base_url().delete_c/delete_user/.$row->user_id;%20?>
As for the second one, it causes an internal error resulting to the status code 500
Use this. There is no need to write again PHP start because you already started and you forgot to mention . operator.
<a href='.base_url().'delete_c/delete_user/'.$row->user_id.'> <button>Delete</button>
</a>
The following code should work.
<a class="btn" href='.base_url().'delete_c/delete_user/'.$row->user_id.'>
Delete
</a>
500 error code may be cause of you forgot to put . in string concatenation or may be undefined variable used in function.

JSON Response is Undefined

I have a issue with JSON response. In am getting undefined values in JSON response. Here is my JS and PHP Code. I have tried every thing but still it giving me undefined value and when I try to console(response) then it displaying complete html.
Here is the Code Of JS and PHP
//Custom JS To Show Modal Update Box
function updateStudentShow($id){
$.ajax({
method:"GET",
url:"view.php",
data:{id:$id},
datatype:"JSON",
success:function(data){
$("#update_name").val(data.name);
$("#update_about").val(data.des);
alert(data.name);
console.log(data);
}
});
$("#update").modal("show");
}
//PHP CODE
<?php
include("connect.php");
$response=array();
if(isset($_GET['id'])){
$id=mysqli_real_escape_string($_GET['id']);
$q="select * from student_details where id='$id'";
}
else{
$q="select * from student_details";
}
$result_students=mysqli_query($con,$q);
while($row_students=mysqli_fetch_assoc($result_students)){
if(isset($_GET['id'])){
$response=$row_students;
}
else{
$id=$row_students['id'];
$name=$row_students['name'];
$des=$row_students['des'];
$image=$row_students['image'];
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $des; ?></td>
<td><img width="60" height="60" src="<?php echo $image; ?>"></td>
<td style="width:20%;">
<a href="javascript:void(0)" onclick="deleteStudent(this.id)" id="<?php echo $id; ?>">
<span style="padding-right:10%;" class="glyphicon glyphicon-trash"></span>
</a>
<a href="javascript:void(0)" onclick="updateStudentShow(this.id)" id="<?php echo $id; ?>">
<span style="padding-right:10%;" class="glyphicon glyphicon-pencil"></span>
</a>
<span class="glyphicon glyphicon-download-alt"></span>
</td>
</tr>
<?php } } ?>
<!--Loop Closed-->
<?php
if(isset($_GET['id'])){
$response=json_encode($response);
echo $response;
}
if(mysqli_num_rows($result_students)==0){
?>
<tr>
<td colspan="5">No Records</td>
</tr>
<?php } ?>
You are outputting the data as html table before echoing your json response.
Your jquery is expecting json only.
To test the output of your script, simply visit the php script in a browser and add the id parameter
http://host/.../view.php?id=1
Overall I think you need to split your code into two files.
One that delivers the javascript and interface.
One that delivers the data (json)
lets call the html output file view.php and the data output file data.php
view.php will contain the javascript which will use data.php in the ajax call to get its json data.
data.php will contain the code to retrieve records from the database and output them as json.
You can't use json_encode() on a table row. Notice up near the top of your html/php, you're doing $row_students=mysqli_fetch_assoc($result_students) followed by $response=$row_students; and then at the bottom you're doing $response=json_encode($response);. See the documentation for json_encode(), which says that the argument value that you pass to json_endcode() can be any type except a resource.
It then links you to the appendix, where you can find out what counts as a resource. The response from mysqli_fetch_assoc() is indeed a resource. It can't be passed to json_encode().

update table row and save in database in php codeigniter

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.

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;
});

Categories