Codeigniter tutorial delete Post doesn't work - php

After completing the tutorial from the codeigniter user guide I ran into a problem I was forcing for the last two hours. I am trying to add functionality to delete a post, selected by ID, I am new to PHP and couldn't find any solution for my problem:
The Controller
public function delete($id){
$id = $this->uri->segment(3);
$data['title'] = 'Delete an item';
if($this->news_model->delete_news($id)){
$this->load->view('templates/header', $data);
$this->load->view('news/success');
$this->load->view('templates/footer');
}else{
}
}
The Model
public function delete_news($id){
$this->db->where('id',$id)->delete('news');
return $this->db->affected_rows();
}
The Routing
$route['news/delete/(:num)'] = 'news/delete/$1';
I'm calling the function out of the index-page where all posts are shown with an anchor:
<p>Delete article</p>
and it calls the correct URL (http://localhost/webapp/index.php/news/delete/2) which should correctly execute and delete the post with the ID 2 from my news table.
I really can't understand where the mistake ism but by executing this, I get a 404.
What am I doing wrong?

In your function delete I don't see that you loaded the news_model. That could be the issue if it isn't auto-loading. Perhaps, start by verifying that the controller is talking to the model by inserting:
echo 'Hello Model';
in the delete_news function of your news_model.
EDIT:
Instead of
if($this->news_model->delete_news($id)){
//conditions
}
And
Have your model send a T/F based on it's execution. This will tell us if the error is in the SQL. By returning TRUE no matter what, we'll see if that model function even runs:
return TRUE;
Try to add the step (for error checking)
$del = $this->news_model->delete_news($id);
echo 'del';
if($del == TRUE){
//conditions
}
With the 404 - I'm also suspicious it's a routing issue. I'll take a look at that as well.

Related

How to remove the $_GET variable after processing it in Laravel?

So I got a little problem. I'm currently learning how to handle laravel. I was okay until now. I`ve tried to create a small page. 4 Articles, 1 Basket, when I click a button, I just hand over the id and the name of the article via $_GET and put it into the basket. This is the controller i have for now:
class FileviewController extends BaseController {
protected $layout = "layouts.master";
public function getIndex() {
if(isset($_GET["article"])) {
Session::push("basket.items", filter_var($_GET["article"]));
$items = Session::all();
}
$articles = Article::with('manufacturer')->get();
}
$articles = Article::with('manufacturer')->get();
$this->layout->content = View::make("article.index", array("items" => $items, "articles" => $articles));
}
At first ive tried to use header() and redirect him on the current page without the parameeter ... didnt work for some reason:
if(isset($_GET["article_id"])) {
Session::push("basket.item_id", filter_var($_GET["article_id"]));
Session::push("basket.item_name", filter_var($_GET["article_name"]));
$items = Session::all();
$articles = Article::with('manufacturer')->get();
header('Location: http://10.36.155.40/laravel/public/article');
}
Didn't work out. Is there any other way to remove the variables from the URL after they have been processed? Because even if the user reloads, the variable is still there and will be added to the basket again. For obvious reasons, i have to avoid that.
I guess i just cant see the forest because of all the trees. Is there even an easier way to do that?
Any help is appreciated. :)
You should just redirect them using Laravels Redirect facade. Gone are the days of setting Location headers! Full docs located here. Here are a few examples:
return Redirect::to('/');
return Redirect::route('my.named.route');
return Redirect::back()->with('errorMessage', 'Get out of here!');

CodeIgniter - Query array output three times instead one

Output is wrong , i Got three the same comment instead only one.
Can anyone help to make only one comment.
Here my view php code:
$modelid = "5" ;
$query = $this->db->query('SELECT message FROM message WHERE modelid = '.$modelid.' ');
$row = $query->row();
echo $row->message;
and my Table:
http://dev.interactive-creation-works.net/Stack/table.png
The controller:
class Comment extends CI_Controller
{
function index()
{
$data['result'] = $this->db->get('message')->result();
$this->load->view('commentView',$data);
}
function insert()
{
$this->load->model('commentjquery');
echo $this->commentjquery->inserttodb();
}
}
This view should only show one message, even if you do - for whatever reason, correctly or not - get three messages from the query. You may be loading the view three times in your controller. Try adding some static text to the top and bottom of your view, and see if it shows up multiple times.
Edit:
Now that you've posted the controller, I can see that's not the issue. But I notice you're trying to grab the comments from the database twice - once in the controller and once in the model. The one in the controller is actually the wrong way to do it unless you've implemented an ActiveRecord model for your comments, and you're not using the results anyway.
Another thing I noticed just now is that you're calling $query->row() instead of running a foreach over $query->result(). Try this:
foreach($query->result() as $row) {
echo $row->message;
}
Edit 2: Or maybe it is the problem, if the code snippet you posted isn't the entire view, which seems to be the case.
It's really weird that you aren't getting error. It gets weirder when you get three outputs.
Change your query to this.
$query = $this->db->query('SELECT message FROM message WHERE modelid = "'.$modelid.'"');

How do i call the function I created in my Model on the view

I just created this function in the model to see who im following in my social network... how do i call it in the view??
function isfollowing($following){
$user_id = $this->session->userdata('uid');
$this->db->select('*');
$this->db->from('membership');
$this->db->join('following', "membership.id = following.tofollow_id");
$this->db->where("tofollow_id","$following");
$this->db->where("user_id", "$user_id");
$q = $this->db->get();
if($q->num_rows() > 0) {
return "yes";
} else {
return "no";
}
}
Now in my VIEW how do i call it being that i had already made a function to get the current logged on user's id and that is equal to $r->id
How do i call it here?? what goes after the "==" in that if statement?
THE VIEW
<?php if ( $r->id == ): ?>
It is not a good practice to call model function from view.
There are some alternatives about it. You can use anyone you like.
First
When you are loading a view call your model function and pass it in a variable
than this variable will be passed to view.
Controller
$following_status = $this->my_model->isfollowing($following);
$data['following_status'] = $following_status;
$this->load->view('my_view',$data);
View
<p>$following_status</p>
Secound
If you want to be independent of model you can create helper which you can
use anywhere in the application. You will have to create a CI instance to
get it working.
custom_helper.php
function isfollowing($following)
{
$CI = get_instance();
$user_id = $CI->session->userdata('uid');
$CI->db->select('*');
$CI->db->from('membership');
$CI->db->join('following', "membership.id = following.tofollow_id");
$CI->db->where("tofollow_id","$following");
$CI->db->where("user_id", "$user_id");
$q = $CI->db->get();
if($q->num_rows() > 0) {
return "yes";
} else {
return "no";
}
}
View
//load the custom helper before using it (you can autoload of in autoload.php)
//or use common way $this->load->helper('custom');
<p>isfollowing($yourparameter)</p>
You do the following:
(1) Load your model in the controller that creates your page or auto load it
(2) In your view, type something like:
$this->The_custom_model->isfollowing($theinputvariable)
where The_custom_model is the model where you defined the isfollowing() function.
$theinputvariable is the appropriate argument value for your function. Keep in mind that you have specified an object as the argument to your function so you need to think about that.
this is an amended version to what raheel posted showing an if check - probably not necessary for your question, but to give you some things to think about...
// check to see if anything come back from the database?
if ( ! $data['following_status'] = $this->my_model->isfollowing($following) ) {
// nothing came back, jump to another method to deal with it
$this->noFollowers() ; }
// else we have a result, and its already set to data, so ready to go
else {
// do more here, call your view, etc
}
databases can go down even if the web page is working so its good to get in the habit of checking the results. the more error checks you can do in your controller and models, the cleaner your view files will be.
To access model into your view you first load it into autoload file like this
$autoload['model'] = array('model_name');
then in view you can get it by using this line of code
$this->model_name->isfollowing($following)
in isfollowing you will pass your tofollow_id

Where to put code in Model View or Controller to manage User priviliges and url manipulation protection in cakephp?

Apologies if this has been asked before, I've done a search and haven't found anything specific. This is has been helpful http://bakery.cakephp.org/articles/Auzigog/2008/12/29/where-should-my-code-go
I'm trying to fix some code I inherited and I found you can change anyone's password, just change the URL:
/site/user/changepassword/(insert id)
I then placed in the user controller, pardon my pseudocode:
if(session.user_id == id_from_link)
view changepasswordform(id_from_link)
else
warn_and_redirect();
I think that was the right thing to do and in the right place?
Now in the Views I find code like this:
if(user_type is admin)
echo admin options
if(user_type is user)
echo user options
Now shouldn't that ideally be the View just having:
echo options
and then the Controller has:
switch(user_type)
case: admin
options = admin stuff
case: user
options = user stuff
and so on? or should this be in the User Model?
Just remove the id parameter from the url... and at the top of the controller action add this:
function changepassword(){
$id = $this->Auth->user('id');
....
}
Now the password will only be changed on the current user that is logged in. Be sure to do your normal checks of making sure $id is not null.
View should effectively be print statements:
<title><?=$this->data['title']?></title>
...
<h1><?=$this->data['main_menu']?></h1>
Controller should prep the view/handle the request:
if(loggedInUser) {
$this->data['title'] = model->getTitle(userID);
$this->redirect(/somepage);
}
else {
$this->redirect(/loginpage);
}
Model should have:
function getTitle($userID) {
this->doStuff($userID);
$title = this->talkToDB($userID);
return $title;
}

jQuery post call with codeigniter fails

I am trying to delete the element with post jquery request:
$(function(){
//The element
// <a data-id="39" data-toggle="modal" href="#delete"><i class="icon-trash"></i>
Delete</a>
$('.delete').on('click',function(){
var id= $(this).attr('data-id');
$.post('task/delete', { id: id }, function(data) {
alert('Task deleted!');
})
.success(function(){ alert('Task deleted!'); })
.complete(function(){ alert('Task completed!'); })
.error(function(){ alert('Error was found!'); });
})
});
My controller is called task and the function inside it is called delete.
class Task extends CI_Controller {
public function delete()
{
$this->load->model('tasks_model','task_delete');
$this->task_delete-> deleteTask($_POST['id']);
}
}
The model is quite simple.. it simply deletes the record.
public function deleteTask($task_id)
{
$task_id = mysql_real_escape_string($task_id);
$this->db->query("DELETE FROM tasks WHERE task_id = ?", array($task_id));
}
I get two messages..one is error and one is delete...
Another thing that I want to avoid is someone posting the id to the controller task .. which will delete the records one by one automatically, is there a way to avoid this too?
Your controller method should look something like this
public function delete()
{
// Do user validation here
$this->load->model('tasks_model');
$this->tasks_model->task_delete($this->input->post('id'));
return "task deleted";
}
And you models method like this
public function task_delete($task_id)
{
$this->db->where('task_id', $task_id);
$this->db->delete('tasks');
}
As I would recommend validating the user where the comment says you should, and using CI's active record library where you can to increase portability to a different DB.
Edit
To show PHP errors (and maybe MySQL errors if they are turned on).
error_reporting(E_ALL);
To ensure the task is deleted, do this (which is not as efficient).
public function task_delete($task_id)
{
$this->db->where('task_id', $task_id);
$this->db->delete('tasks');
$this->db->from('tasks');
$this->db->where('task_id', $task_id);
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
return FALSE;
}
else return TRUE;
}
And then do something with the returned boolean in the controller.
You haven't used the function name in your controller it should be:
$this->task_delete->deleteTask($id);
To avoid someone posting all IDs and deleting all tasks, you should only delete tasks which belong to this user.
I'm guessing you save each task so it belongs to a specific user, right? So in your delete query, you can make it so you run a DELETE WHERE task_id={task_id} AND user_id={user_id}. The user_id is something you'll have saved in the session.
As a side note, when running database queries, you can bind the parameters, which means CI takes care of making the parameters safe. So you can amend your query above to be like this:
$this->db->query("DELETE FROM tasks WHERE task_id = ?", array($task_id));
You can read more on this here: http://codeigniter.com/user_guide/database/queries.html at the bottom (Query Bindings section).
As for your error of getting both an error and a success message, there might be a few different things going wrong. I'm not sure if something's gone wrong when copying the code, but you have an error in the PHP code:
$this->load->model('tasks_model','task_delete');
$this->task_delete($id);
Should be:
$id = $this->input->post('id'); // the data is posted, it won't be passed in as an argument to the controller function
$this->load->model('tasks_model','task_delete');
$this->task_delete->deleteTask($id);
And your query also seems to have a mistake, so it would be better to make it as I mentioned above.

Categories