Delete database entry in codeigniter - php

I am working on a project which is designed in Codeigniter. I am new to the Codeigniter framework/php and trying to learn the same. Currently I have a page which displays the table of all the results. I want to have the option of being able to delete whichever row I want to. I've added the function in model and controller and a delete icon is present in the view but I am not sure how to co-ordinate the same.
Function in Model:
function delete_row($job){
$querystr = 'delete from jobs where job = \''.$job.'\'';
$query = $this->db->query($querystr);
$arr = $query->result_array();
$query->free_result();
return ;
}
Function in Controller:
public function delete(){
$this->load->model('Job');
$this->Job->delete_row($job);
$this->load->view('my_view');
return;
}
View:(my_view.php (snippet))
if($key==='job'){
echo "<input type = 'image' src = '/home/Downloads/DeleteButtonSmall.png' width='20' height ='15' name ='delete_box' >"; }
The view has lot of functions in it but this above line is the one which enable the delete image to all the rows visible on the display.
Please don't be harsh. Any suggestion on how to get this working. Also if the question isnt clear, feel free to post that in the comment. I will try to elaborate as much as I can.

Your question is not clear, but if you want to call a function in the controller (in this case delete) without refreshing you need to use ajax. and to give you more freedom use jQuery too.
here is a simple thing to give you an idea. http://jsfiddle.net/KV3WF/4/
in your controller you need to echo 1 if you deleted successfully and 0 if not.
i hope i helped in my answer if you found anything not clear please do ask.
if you want also you dont have to put onclick in html you can do it in javascript
$( document ).ready(function() {
$('#category').click(function(){ //you just give an id to whatever you want to select plus you can do it by selecting a class instead id..... so you can give multiple buttons the same class("category")
//DO the same ajax function in the jsfiddle.
});
//end of doc.ready
});
P.S. try to practice not to delete from the database, add a column named (hide) and update it to 1 (default is 0) when you want to delete.

Not sure if I understand your question, but from what I understand you are trying to delete a row based on what data you clicked
on your model you could try the Active Record Pattern for delete
Model
function delete_row($job){
$this->db->where('job', $job);
$this->db->delete('jobs');
// DELETE from jobs WHERE job = $job
}
On your controller, this is where you will pass the your identifier from the view so that it can interact with the model.
Controller
function delete($id = '')
{
$this->load->model->('Job');
$this->Job->delete_row($id);
redirect('to jobs view')
}
then on your view, you could define a link that calls your delete method in the controller and deletes a row based on the parameter you passed in the URI
say, if you pass something like this
www.example.com/controller/delete/worker
It would delete the row where job = worker
View
you could do it like this
<a href="controller/delete/worker">
<img src = '/home/Downloads/DeleteButtonSmall.png' width='20' height ='15' />
</a>

Related

Save fileds changes with ajax in laravel

I want to change some parts of my data from index page without loading edit page with Ajax.
For example my reviews has status where value is 0 or 1 and also comment section. I want to change these values from my index page.
All the code i have is simply my index method only, where i load my list
public function index()
{
$ratings = Rating::orderby('id', 'desc')->paginate(10);
return view('admin.ratings.index', compact('ratings'));
}
I need help to make my index page as a form with Ajax in order to edit from there but not to use my Update method because I'll need it for my edit.blade.php (maybe add another method in my controller?)
Thanks.
First of all you need a controller that updates the post status. As discussed it totally up to you want you want to do.
My suggestion is to create a new controller called UpdatePostStatusController and then have update method that takes post id and the status either 1 or 0 and update it.
Your index file should have javascript that gets triggred everytime you change the status like so
checkbox html
<input type="checkbox" data-uuid="{{ $post->id }}" class="update" #if($post->status) checked #endif/>
Now your ajax should
$('.update').change(function() {
data = {'status' : this.checked }
post_id = $(this).data('uuid');
//do your ajax post request here here
}

Laravel (Beginner) - Display data from a selected row from a dropdown

This is Controller.php
public function dropdown($id)
{
$stations = Station::lists('station_name','id');
return view('stations.show')->withStation($station);
return view('stations.dropdown',compact('stations', 'selectedStation','selectedStation'));
}
This is the view.php
{{ Form::select('station',$stations,null,['class' => 'form-control']) }}
<br>
<?php
if(isset($_GET['submit'])){
$selectedStation = $_GET['station'];
echo $selectedStation;echo "<br>";
}
else
{
echo "not working";
}
?>
corresponding Database table.
This gives me a drop-down like in the below image.
When a station is selected it displays only "id" of the selected station. How to retrieve other columns of the selected station ?.
Many ways that you can tackle this and I have also made some assumptions.
Your list (it would seem) only contains the name & the id.
I assume that you don't want to reload the page when you get the information for the specific item that you have chosen in the dropdown.
Here are the first 2 options that come to mind.
1.) AJAX - Use javascript framework like jQuery and monitor change() for the select, on change get the id and fire it to another route in Laravel which takes the ID and returns some more information in JSON. You can then use JS to display this to your users as you please.
2.) Preloaded JSON - Write new DB Query that gets all the information that you want and store it in JSON format inside some <script> tags. It wont be viewable to the user. Then you can use jQuery or other JS framework to grab that data again on change()
Part 2 will be faster, and if you have got 100,000s records i would advise that for perf.
Apologies if I totally misunderstood the question, it seems like you need a JS solution rather than Laravel/PHP solution. (Without a bad UX) if you did wan't more data you would need to post it and the fetch data from DB on new request.
To display all the columns of all stations you can do the following.
Please note, doing this you fetch all which may not be necessary and there may be better methods available on the eloquent model class depending on what you are trying to do.
Controller
public function showTable()
{
//Fetch all stations from the database
$stations = Station::all();
//Return fetched data to the view
return view('stations.show', ['stations' => $stations]);
}
View - stations/view.blade.php
<ul>
#foreach ($stations as $station)
<li>{{$station->station_name}} - {{$station->rainfall}}</li>
#endforeach
</ul>
For more information and examples about the eloquent model class you can check: https://laravel.com/docs/5.2/eloquent

PHP: Confirm Box before deleting

I want to add a button on my website, where a User can delete his Account. Unfortunately I don't know how to realize it...
my Code so far:
Javascript:
<script language = "JavaScript" >
function delete(id) {
if (confirm("Do your really want to delete your account?"))
{
header("refresh:1;url=intern.php?act=account");
}
else
{
}
}
</script>
my .html file:(there are no tags like html title head... it begins with ?php..)
<td></form><input type='submit' name='deleteuser' value='Delete Account' onClick='return delete()'/></form></td>
Also i have an if clause in the .html file:
if(isset($_POST['deleteuser'])) {
if(delete() == true){
delete_user;
}
else{
header("refresh:1;url=intern.php?act=account");
}
}
The Button is there and when I click on it, it asks me if I'm sure to delete my account, but afterwards I got an error: "Fatal Error:Call to undefined function delete() "
I have a stored procedure named: sp_deleteAccount. In my config.php I declared it as:
$SQL_delete_user = "CALL sp_deleteAccount('";
Now I don't know how to bind that stored procedure in the code so that the Account will be deleted after pressing "Yes I want to delete my Account".
Hope I didn't miss anything and someone can help me
JOP
In this portion you're calling a php redirect(i think?) in javascript without php open tag so that's not going to work. Instead you can use a javascript reditrect if the 'if' statement returns true(yes) then redirect to a url with a get variable of delete or something, see below.
edit -- you'll probably want the id as well so i made adjustments. PLus in the onclick in the form you'll need to pass the id, unless it's stored in a session variable or something, in which case you don't need to pass it into the url. your sql should end with "WHERE id=" then just tack the id onto the query. This is just a simple example to get you started, always be cautious of sql injection, but i'll leave preventing it up to you.
<script language = "JavaScript" >
function deleteUser(id) {
if (confirm("Do your really want to delete your account?"))
{
window.location.href= 'intern.php?delete=true&id='+id;
}
else
{
window.location.href = 'intern.php?act=account';
}
}
</script>
next in intern.php check for the get variable
if(isset($_GET['delete'])) {
$mysqli = new mysqli(connection variables here);
$mysqli->query($SQL_delete_user.(int)$_GET['id']);
}
give that a try, rearrange the code as you like but that should get it done.
as for the error, you can't use the keyword delete for a function name. One last thing, for this to work make the input type "button"
I am not sure there might be a way to achieve it using the approach you are trying , but I am not aware of it. For this I would typically use an ajax call to an url, on the click event of the OK button in the jquery-ui Dialog. And then process the logic and on success create another dialog for confirmation.
I searched and struggled with this issue until I did a little lateral thinking.
I used JavaScript to show a hidden div containing the Yes/No options.
Then an onClick around the Yes option which loaded the php script into a hidden iFrame.
The onClick around the No option simply hid the div and did nothing else.
A bonus is being able to style the div any way I wanted, show and hide it with an effect and place it exactly where it looked best.

Add fragment to url during php runtime

Ok so here's my situation: I have a page with 5 jquery-ui tabs, 3 of them contain a table each that is generated by php for the data, with each of them there's a set of input to filter according to the date, each table have their own form and update button. Now what I want to achieve is once I refresh and get back to the controller I want to add the corresponding fragment according to the button I pressed.
For example: If I click on the update button from the first tab I want to add #tabs-1, if it's the second one then I want to add #tabs-2.
Now I know I can do:
$_SERVER['SCRIPT_URI'] = $_SERVER['SCRIPT_URI'] . "#tabs-2";
Fine that gives me the correct url, but how do I make the browser go there at runtime? Is there any way to do this?
Here's a part of my controller, the main one.
class PageOptimisationV2C {
public static function main() {
$class = __CLASS__;
$c = new $class;
$c->get();
}
public function get() {
$this->display();
}
private function display() {
$tpl = new PageOptimisationV2V();
$client = ConsulterClient::getClientByNoClient(isset($_GET['cid']) ? $_GET['cid'] : 0);
$tpl->client = $client;
if(isset($_GET['cid'])){
$tpl->StatsLignesCellulaire = self::buildCellStatsReport();
}
$_SERVER['SCRIPT_URI'] = $_SERVER['SCRIPT_URI'] . "#tabs-2";
$tpl->display();
}
}
And then it goes on and displays the page. What would be the optimal solution to get to a fragment of the page, according to the submit button that is pressed.
I tried to make a jsFiddle to show you how the page looked but it got too messy and couldn't get the CSS to work right.
Every detail of information is appreciated.
The only way i'm aware of to do this with PHP is to do a redirect.
header('Location: ' . $_SERVER['REQUEST_URI'] .'#tabs-2');
This of course will result in another request and require you to do some workaround with your flow but its the only way to send a new url back to the browser.
Though it isn't a runtime PHP method you can also just embed the selection Javascript, for example:
var index = $.index($(<?PHP echo $tab; ?>));
$('#tabs ul').tabs('select', index);
and allow it to go through the normal selection process.
You can also just embed a hidden element, something like
<input type="hidden" name="tab-selected" id="tab-selected" value="tabs-2" />
and have some Javascript to check if the element exists and has a value and then select the tab like this:
$(function() {
if ($('#tab-selected').val()) {
var index = $.index($('#tab-selected').val()));
$('#tabs ul').tabs('select', index);
}
});
Today, with a fresh mind, I thought of something else to do while reading MWJump's answer... Why not use the action attribute of the form! It's there for a reason! So for each of my form (I have one in each of my tabs) I slapped the action attribute to be the fragment of the according tab so for the first tab action="#tabs-1" and the second action="#tabs2" and so on...
I found this solution to be the simplest and easiest in this particular case.

Is it possible to force the value of a new CRUD form field?

I am using Agile Toolkit. I have a drop-down field in my CRUD.
How can I make the "New" button display different set of values in this drop-down to when the "Edit" button is clicked?
Here is my code:
class page_things extends Page {
function init(){
parent::init();
$p = $this;
$f = $p->add('Form');
$idCat = ($f->get('idCat')?$f->get('idCat'):$this->api->getConfig('idCat','MASP2U03'));
$dpUE = $f->addField('dropdown', 'Category');
$dpUE->setModel('Category');
$dpUE->js('change',$f->js()->submit());
$dpUE->set($idCat);
$f->addSubmit('OK');
$c = $f->add('CRUD');
$c->setModel('things',array('name', 'field1', 'field2', 'field3'))->setMasterField('idCat',$idCat);
if($f->isSubmitted()){
$c->js(true)->show()->execute()->reload()->execute();
}
}
}
Thank you for help !!
use
$crud=$this->add('CRUD',array('allow_add'=>false));
to disable default Add button, then add your own button:
if($crud->grid)$crud->grid->addButton('Add')->js('click')
->frameURL('Add',$this->api->url('./new'));
After this you'll need to create a new page
class page_things_new extends Page {
and inside this page define the form the way you want it to appear no the "add" click. I don't fully understand your question, but with these instruction you can have a different page appear when adding new entries to your crud.
Here's an alternative to Romans that I've tried. It uses $this->api->memorize to store a GET variable chosen in the drop down list in a session variable. Then in the Form, you can set default the chosen value by using recall in the model.
Something like this
in page/things
// load the javascript function (see later)
$this->js()->_load('your_univ');
/*****************************************************************/
/* Code to populate drop down lists - amend where as required*/
$catList=$this->api->db->dsql()->table('category c')
->field('c.id')
->field('c.name')
->where('c.type',$cat_type)
->order('c.id')
->do_getAssoc();
// Check if one is set on URL or default from config and memorize the value
if ($_GET['cat']){
$cat=$_GET['cat'];
} else {
$cat=$this->api-getConfig('idCat');
}
$this->api->memorize('category',$cat);
$f=$p->add('Form',null,null,array('form_empty'))
->setFormClass('horizontal bottom-padded');
$l1=$f->addField('dropdown','category')->setValueList($catList)->set($cat);
// calls a bit of javascript described later to reload with the parameter
$l1->js('change')->univ()->yourfunc($p->api->getDestinationURL(null), $l1);
.. rest of your page code goes here ..
Then in /lib/Model/Category.php
Add the following recall for the field
$this->addField('idCat')->system(true)->visible(false)
->defaultValue($this->api->recall('category'));
Note the system(true) and visible(False) means it wont show up and wont be changeable on the CRUD but you can play around with the options so it shows in the CRUD grid but not in the form.
Finally, the little bit of javascript to make the reload work (Romans might advise a better way to do this). Make sure yourfunc matches in the page and in the js.
in /templates/js/your_univ.js add the following
$.each({
yourfunc: function(url, name){
document.location.href=url+'&cat='+$(name).val();
},
},$.univ._import);
I've got code similar to this working in my own pages. You can probably make it work as a POST as well as the drop down is a form if you dont want the cat to show on the URL.

Categories