Remove image from folder after deleting in codeigniter - php

I want to delete the image not only in database, but in folder too.
this is my model
public function delete($id)
{
if ($this->db->delete("np_gallery", "id = ".$id))
{
return true;
}
}
this is my controller
public function delete_image($id)
{
$this->np_gallery_model->delete($id);
$query = $this->db->get("np_gallery");
$data['records'] = $query->result();
$this->load->view('admin/gallery/gallery_listing',$data);
}
this is my view
<table class="table table-bordered">
<thead>
<tr>
<td>Sl No</td>
<td>Tag</td>
<td>Image</td>
<td>Action</td>
</tr>
</thead>
<?php
$SlNo=1;
foreach($records as $r)
{
?>
<tbody>
<tr>
<?php $image_path = base_url().'uploads';?>
<td><?php echo $SlNo++ ; ?></td>
<td><?php echo $r->tag; ?></td>
<td><img src="<?php echo $image_path; ?>/images/gallery/<?php echo $r->picture;?>" style=" width:35%; height:100px;"/></td>
<td>
</td>
</tr>
</tbody>
<?php } ?>
</table>
I succeed in deleting the data in the database, but the image in the folder are not also be deleted.

Add some extra code in your controller:
public function delete_image($id)
{
$image_path = base_url().'uploads/images/gallery/'; // your image path
// get db record from image to be deleted
$query_get_image = $this->db->get_where('np_gallery', array('id' => $id));
foreach ($query_get_image->result() as $record)
{
// delete file, if exists...
$filename = $image_path . $record->picture;
if (file_exists($filename))
{
unlink($filename);
}
// ...and continue with your code
$this->np_gallery_model->delete($id);
$query = $this->db->get("np_gallery");
$data['records'] = $query->result();
$this->load->view('admin/gallery/gallery_listing',$data);
}
}
Note: alternativelly, you can do it inside your model delete() method instead. Consider where it better fits your applicaction needs.

Try these
foreach ($query_get_image->result() as $record)
{
// delete file, if exists...
$filename = $image_path . $record->picture;
if (file_exists($filename))
{
unlink($filename);
}
// ...and continue with your code
$this->np_gallery_model->delete($id);
$query = $this->db->get("np_gallery");
$data['records'] = $query->result();
$this->load->view('admin/gallery/gallery_listing',$data);
}

Related

how to access the value of blob column(image) in controller laravel

I make live search in laravel by ajax jquery
i send html code from controller to view but i can't display the value of blob column
function search (Request $request) {
if($request->ajax())
{ $output='';
$data=Club::all();
foreach($data as $record)
{
$output.='
<tr>
<td > '.$record->name.'</td>
<td > '.$record->country.'</td>
<td ><img src="data:image/png;charset=utf8;base64,{{base64_encode('.$record-
>logo.')}}" ></img></td> //this is uncorrect what is the correct syntax here???
</tr>
';
}
echo json_encode($output);
}
}
Try to return the data rather than display them using echo
json_encode() shall receive object or array, not HTML, return data from your API then format it in front-end.
if($request->ajax())
{ $output='';
$data=Club::all();
return json_encode($data); \\ return rather than display
}
if($request->ajax())
{
$output='';
$data=Club::all();
$path = $record->logo;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
foreach($data as $record)
{
$output.='
<tr>
<td > '.$record->name.'</td>
<td > '.$record->country.'</td>
<td ><img src="'.$base64.'" ></img></td> //this is uncorrect what is the correct syntax here???
</tr>
';
}
echo json_encode($output);
}

Show table data based on ID in codeigniter

I have a table that store the data of ID, ID Login, Name, etc. But i just want to show the data based on ID Login
Here My Controller :
function index(){
$data['hasil'] = $this->M_user_lapor->index_model();
$this->load->view('v_user_lapor/index', $data);
}
My Model :
function index_model(){
$baca = $this->db->query('select * from user_lapor');
if($baca->num_rows() > 0){
foreach ($baca->result() as $data){
$hasil[] = array(
'id_login'=>$data->id_login,
'id_lapor'=>$data->id_lapor,
'nm_unit'=>$data->nm_unit,
'pic_1'=>$data->pic_1,
'pic_2'=>$data->pic_2,
'ip_wan'=>$data->ip_wan,
'ip_lan'=>$data->ip_lan,
'prov'=>$data->prov,
'icn_sid'=>$data->icn_sid,
'tlkm_sid'=>$data->tlkm_sid,
'status'=>$data->status,
);
}
return json_encode ($hasil);
}else{
return false;
}
}
View :
<tbody>
<?php
if ($hasil){
$no = 1;
$array = json_decode($hasil, true);
foreach($array as $data) {
?>
<tr>
<td class="text-center"><?php echo $no++;?></td>
<td><?php echo $data['nm_unit'];?></td>
<td><?php echo $data['pic_1'];?></td>
<td><?php echo $data['pic_2'];?></td>
<td><?php echo $data['ip_wan'];?></td>
<td><?php echo $data['ip_lan'];?></td>
<td><?php echo $data['prov'];?></td>
<td><?php echo $data['icn_sid'];?></td>
<td><?php echo $data['tlkm_sid'];?></td>
</tr>
<?php
}
}
?>
</tbody>
As you can see, there is id_login inside my model, and i want to show the table data based on it, hopefully somebody can help me because i'm just using the codeigniter, thnaks
I solved this by myself, lol. I just pass the id_login value from session, so i add this to my controller :
function index(){
$id_login = $this->session->id_login;
$data['hasil'] = $this->M_user_lapor->index_model($id_login);
$this->load->view('v_user_lapor/index', $data);
}
And call it to my model :
function index_model($id_login){
$baca = $this->db->query('select * from user_lapor where id_login='.$id_login);
if($baca->num_rows() > 0){
foreach ($baca->result() as $data){
$hasil[] = array(
'id_login'=>$data->id_login,
'id_lapor'=>$data->id_lapor,
'nm_unit'=>$data->nm_unit,
'pic_1'=>$data->pic_1,
'pic_2'=>$data->pic_2,
'ip_wan'=>$data->ip_wan,
'ip_lan'=>$data->ip_lan,
'prov'=>$data->prov,
'icn_sid'=>$data->icn_sid,
'tlkm_sid'=>$data->tlkm_sid,
'status'=>$data->status,
);
}
return json_encode ($hasil);
}else{
return false;
}
}

Undefined variable,index error fetching data codeigniter

Im fetching data from a table to another table that will be shown in my dashboard page for a user after loggin in.
But there is a problem with the indexes, i got this error:
Here is the line error:
Here is my code:
My view file ("usuario"):
<thead>
<th>id</th>
<th>User</th>
<th>Subject</th>
<th>Grade</th>
<th>Date</th>
</thead>
<tbody>
<?php
if (count($records) > 0 && $records != false) {
foreach($records as $record) {
echo "<tr>
<td>".$record['id']."</td>
<td>".$record['User']."</td>
<td>".$record['name']."</td>
<td>".$record['grade']."</td>
<td>".$record['date']."</td>
</tr>";
}
}
?>
</tbody>
</body>
</html>
My controller file ("login"):
public function home(){
$data['record']=$this->m_login->getDetails();
$this->load->view('usuario',$data);
}
My model file ("m_login"):
public function getDetails()
{
$st=$this->db->SELECT('cursadas.*, usuarios.name as usuarios, materias.name as materias_name')->from('cursadas')
->join('usuarios','usuarios.id=cursadas.user_id')
->join('materias','materias.id=cursadas.subject_id')
->WHERE('cursadas.user_id=',$this->session->userdata['id'])
->get()->result_array();
return $st[0];
}
You have the variable $records on view but not on controller
Change
$data['record'] = $this->m_login->getDetails();
To
// add this array() just in case no results found
$data['records'] = array();
$data['records'] = $this->m_login->getDetails();
$this->load->view('usuario', $data);
Another way is on controller
$results = $this->m_login->getDetails();
$data['records'] = array();
if ($results) {
foreach ($results as $result) {
$data['records'][] = array(
'id' => $result['id'],
'User' => $result['User'],
'name' => $result['name'],
'grade' => $result['grade'],
'date' => $result['date']
);
}
}
$this->load->view('usuario',$data);
View
<?php if ($records) {?>
<?php foreach($records as $record) {?>
<tr>
<td><?php echo $record['id'];?></td>
<td><?php echo $record['User'];?></td>
<td><?php echo $record['name'];?></td>
<td><?php echo $record['grade'];?></td>
<td><?php echo $record['date'];?></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td>No Results Found</td>
</tr>
<?php } ?>
Wrong array index in your controller.
Change this
$data['record']=$this->m_login->getDetails();
to
$data['records']=$this->m_login->getDetails();
result_array() return returns result with array so you need to it like this -
if (count($record) > 0 && $record != false) {
foreach($record as $rec){
echo "<tr>
<td>".$rec['id']."</td>
<td>".$rec['User']."</td>
<td>".$rec['name']."</td>
<td>".$rec['grade']."</td>
<td>".$rec['date']."</td>
</tr>";
}
}
Please check this from above code and comment if you have any problem

codeigniter - html2pdf (dompdf library) does not show the database results in the generated pdf

I am working with html2pdf (dompdf library), to create a PDF invoice with data from the database.
The pdf is generated with all the formatting css perfectly.
The generated pdf does not show the results of the invoice from the database, in the view I put an "else" statement to see if it was printing actually post something. it is printed empty rows.
The data in the database are there.
Where am I wrong?
Sorry for the bad English.
Thank you.
My Controller:
public function index()
{
//Load the library
$this->load->library('html2pdf');
$this->load->model('model_fatture2');
//Set folder to save PDF to
$this->html2pdf->folder('./assets/pdfs/');
// change name file
$nome_file = "pippo";
//Set the filename to save/download as
$this->html2pdf->filename($nome_file.'.pdf');
//Set the paper defaults
$this->html2pdf->paper('a4', 'portrait');
$data['result_fatture'] = $this->model_fatture2->getFattureUtente();
// test view
$data = array(
'title' => 'PDF Created',
'message' => 'Hello World!'
);
//Load html view
$this->html2pdf->html($this->load->view('pdf', $data, true));
if($this->html2pdf->create('download')) {
//PDF was successfully saved or downloaded
echo 'PDF saved';
}
//$this->output->enable_profiler(TRUE);
}
My Model:
function getFattureUtente() {
$userId = $this->session->userdata('id');
$ProgettoId = $this->session->userdata('id_progetto');
$data = array();
$this->db->select('*');
$this->db->from('fatture');
$this->db->join('users', 'fatture.id_progetto = users.id_progetto');
$this->db->where('id_user',$userId);
$this->db->where('fatture.id_progetto', $ProgettoId);
$query = $this->db->get();
if($query->num_rows() > 0){
foreach ($query->result_array() as $row) {
$data[] = $row;
}
$query->result();
return $data;
}
}
My View
<?php if (!empty($result_fatture)): ?>
<?php foreach ($result_fatture as $row): ?>
<?php if ($this->session->userdata('id') === $row['id']): ?>
<table height="20" border="0" cellpadding="0" cellspacing="0" class="table_riga">
<tr>
<td class="col-dx"><?=$row['id_fatture']?></td>
<td class="col-dx"><?=$row['id_user']?></td>
<td class="col-dx"><?=$row['id_progetto']?></td>
<td class="row-bottom"><?=$row['n_progetto']?></td>
<td class="col-sx"><?=$row['data_emissione']?></td>
<td class="col-sx"><?=$row['n_fattura']?></td>
<td class="col-sx"><?=$row['prezzo']?></td>
</tr>
</table>
<?php endif; ?>
<?php endforeach; ?>
<?php else: ?>
<?php echo "rows empty"; ?>
<?php endif; ?>
SOLVED! I'M NOT HAD DECLARED THE SESSIONS, SO THE VIEW session-> userdata ('id') === $ row ['id']):?> RETURN FALSE. If it can help someone. thanks

Codeigniter 2 not returning from model as object only as result array

So, i've been using codeigniter for a while and I've never had an issue running a query in my model and returning it to my controller which then passes it into my view where I access it as an object, like so:
MODEL (somemodel)
function getdata()
{
$query = $this->db->get('sometable');
return $query;
}
CONTROLLER (somecontroller)
function controldata()
{
$this->load->model('somemodel');
$data['dbdata'] = $this->somemodel->getdata();
$this->load->view('someview',$data);
}
VIEW (someview)
<?php
foreach($dbdata->result() as $row) {
echo $row->id;
echo $row->name;
echo $row->whatever;
echo "<br />";
}
?>
But now for whatever reason in 2.0 it's making use $dbdata->result_array() as $row instead.
Basically it's returning the results as an array instead.
It doesn't make any sense, has something changed in the new version?
Thanks,
So here's my code:
MODEL (admin_model)
function show_allproducts($sort,$order,$limit,$offset)
{
$this->db->select('products.id,productcategories.categoryname,products.name,products.internetspecial,products.added,products.modified');
$this->db->from('products');
$this->db->join('productcategories','products.productcategories_id = productcategories.id');
$this->db->order_by($sort,$order);
$this->db->limit($limit,$offset);
$query = $this->db->get();
if($query->num_rows() > 0)
{
return $query;
}
else
{
return FALSE;
}
}
CONTROLLER (admin)
function show_allproducts()
{
$data['title'] = 'All Products';
$this->load->library('pagination');
$config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/admin/show_allproducts';
$config['total_rows'] = $this->db->get('products')->num_rows();
$config['per_page'] = 10;
$config['num_links'] = 5;
$config['full_tag_open'] = '<div class="paggination right">';
$config['full_tag_close'] = '</div>';
$config['prev_link'] = '< prev';
$config['next_link'] = 'next >';
$config['cur_tag_open'] = '<a class="active">';
$config['cur_tag_close'] = '</a>';
$this->pagination->initialize($config);
$this->load->model('admin_model');
$data['tabledata'] = $this->admin_model->show_allproducts('name','ASC',$config['per_page'],$this->uri->segment(3));
$data['nav'] = 'admin/pagesections/nav';
$data['maincontent'] = 'admin/pages/show_allproducts';
$this->load->view('admin/template',$data);
}
VIEW (show_all_products)
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<?php if($tabledata) { ?>
<tr>
<th>ID</th>
<th>CATEGORY</th>
<th>NAME</th>
<th>ADDED</th>
</tr>
<?php foreach($tabledata->result() as $row) { ?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->categoryname; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->added;) ?></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td>NO DATA</td>
</tr>
<?php } ?>
</table>
Unless you specify $dbdata->result_array() as $row , It wont return the results as array. The same code which you've posted must be working in CI 2.0.
If not, may be the problem with $this->db->get('sometable').
Try with $this->db->query('select * from sometable'). But as far as i know, both are same...
Ok folks, no lie, I found the freaking problem.
Looking at the fourth td where $row->added; is at, there's a close parantheses at the end of it that was causing 4 days of mayhem.
Kindest regards to all those who tried to help. Sometimes it doesn't matter how many eyes are on it I guess.

Categories