I am trying to view my image files taken from the database and i have no idea why i get a undefined variable when loading my view.
Pretty much I am just trying to view the imagenames stored in my database images.
Any help would be great thank you.
Here are the errors i receive when viewing in browser
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: imagename
Filename: layouts/home.php
Line Number: 8
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: layouts/home.php
Line Number: 8
Here is my Controller
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('upload');
}
function index() {
$this->load->model('index_model');
$foldername['foldername'] = $this->index_model->getFoldernames();
$imagename['imagename'] = $this->index_model->getImagenames();
$this->load->view('layouts/home', $foldername, $imagename, array('error' => ' ' ));
}
function create() {
if(array_key_exists('createFolder',$_POST)){
$data = array(
'folderName' => $this->input->post('folderName')
);
$data = str_replace(' ', '_', $data);
$this->index_model->createFolder($data);
}
$this->foldercreated();
}
function delete() {
$this->load->model('index_model');
$foldername['foldername'] = $this->index_model->getFoldernames();
$this->load->view('layouts/delete', $foldername);
}
function deleteFolder() {
if($this->input->post('checkbox') !== false) {
$checkbox = $this->input->post('checkbox');
$this->index_model->deleteFolder($checkbox);
}
$this->folderdeleted();
}
function foldercreated() {
$this->load->view('partials/foldercreated');
}
function folderdeleted() {
$this->load->view('partials/folderdeleted');
}
function do_upload() {
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->upload->initialize($config);
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile'))
{
// echo '<p>IMAGE NOT WORKING</p>'. '<br/><p>' . $this->upload->display_errors() . '</p>';
$uploadError = $this->upload->display_errors();
$this->load->view('partials/upload_error', $uploadError);
}
else
{
// $imagefile = array('upload_data' => $this->upload->data());
$upload_data = $this->upload->data();
$db_data = array('imageName' => $upload_data['file_name']);
$this->index_model->addImage($db_data); // replace the tablename
$this->load->view('partials/upload_success', $db_data);
}
}
}
Here is my Model
function getFolderNames() {
$this->db->order_by('id', 'DESC');
$this->db->select('folderName');
$q = $this->db->get('senior');
if($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
function getImagenames() {
$this->db->order_by('id', 'DESC');
$this->db->select('imageName');
$query = $this->db->get('images');
if($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
}
And Here is my View
<div id="imagefiles">
<?php
foreach ($imagename as $img) { ?>
<div><?php echo $img->imageName; ?></div>
<?php } ?>
</div>
You aren't passing data to your view correctly.
You have this: $this->load->view('layouts/home', $foldername, $imagename, array('error' => ' ' ));
Your second parameter should be an array of data that you want to pass to your view. Try something like this:
$data['foldername'] = $this->index_model->getFoldernames();
$data['imagename'] = $this->index_model->getImagenames();
$this->load->view('layouts/home', $data);
Please check the CodeIgniter documentation for more info.
Related
I have a form which accepts some text input fields and a file field (used to upload image and pdf).
My problem is like that, if I did not fill upload image, i get an error. How to make the error become text default by the function or i mean that empty field change with my function $default_jarkom etc?
The Controller is:
public function tambah()
{
//$file = base_url()."assets/file/".$_FILES['berkas']['name'];
$default_jarkom = base_url()."assets/images/img1.jpg";
$default_android = base_url()."assets/images/img2.jpg";
$file_gambar = base_url()."assets/images/".$_FILES['berkas1']['name'];
if (isset($_POST['nama']) || isset($_POST['deskripsi'])) {
$matkul = $_POST['matkul'];
$dosen = $_POST['dosen'];
$nama = $_POST['nama'];
$deskripsi = $_POST['deskripsi'];
$file = $_FILES['berkas']['name'];
$file_gambar;
$check = $this->db->query(
"SELECT * FROM materi
WHERE nama_materi='$nama'
OR deskripsi='$deskripsi';"
);
$msg = false;
if ($check->num_rows()==0){
$id = $this->materi_model->buat_id();
$simpan = $this->materi_model->tambah(
$id,
$matkul = $_POST['matkul'],
$dosen,
$nama = $_POST['nama'],
$deskripsi = $_POST['deskripsi'],
$file = $_FILES['berkas']['name'],
$file_gambar
);
if ($simpan) {
$this->aksi_upload() ;
$this->aksi_upload1() ;
$msg = true;
}
}
echo json_encode($msg);
}
}
public function aksi_upload(){
$config['upload_path'] = './assets/file/';
$config['allowed_types'] = 'gif|jpg|png|pdf|doc';
$config['max_size'] = 10000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('berkas')){
$error = array('error' => $this->upload->display_errors());
//$this->load->view('data_tugas_mhs', $error);
return $error;
}else{
$data = array('upload_data' => $this->upload->data());
//$this->load->view('data_tugas_mhs', $data);
return $data;
}
}
public function aksi_upload1()
{
$image = FALSE; //by default file is not uploaded
$data = array();
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png|pdf|doc';
$config['max_size'] = 10000;
$this->load->library('upload', $config);
$default_jarkom = base_url()."assets/images/img1.jpg";
if ( ! $this->upload->do_upload('berkas1'))
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
First you should upload before inserting to get the proper uploaded filename. You should also check all your posts to see if they are null otherwise errors can occur. And you should either escape your input or use query builder as you had an insecure query.
I've modified your upload function as well to keep things DRY.
public function tambah() {
$default_jarkom = base_url() . "assets/images/img1.jpg";
$default_android = base_url() . "assets/images/img2.jpg";
$msg = false;
if (isset($_POST['nama']) || isset($_POST['deskripsi'])) {
$nama = $_POST['nama'];
$deskripsi = $_POST['deskripsi'];
$matkul = isset($_POST['matkul']) ? $_POST['matkul'] : '';
$dosen = isset($_POST['dosen']) ? $_POST['dosen'] : '';
// insecure! you aren't escaping! using query builder or escape your data!!!
$this->db->where('nama_materi', $nama);
$this->db->or_where('deskripsi', $deskripsi);
if ($this->db->count_all_results('materi')) {
$file = $this->aksi_upload('berkas', $default_jarkom);
$file_gambar = $this->aksi_upload('berkas1', $default_jarkom);
$id = $this->materi_model->buat_id();
if ($this->materi_model->tambah($id, $matkul, $dosen, $nama, $deskripsi, $file, $file_gambar)) {
$msg = true;
}
}
}
echo json_encode($msg);
}
/**
* Upload function
*
* #param string $field
* #param string $default Failed upload, return this
* #return string
*/
public function aksi_upload($field = 'userfile', $default = '') {
$this->load->library('upload');
$config['upload_path'] = './assets/file/';
$config['allowed_types'] = 'gif|jpg|png|pdf|doc';
$config['max_size'] = 10000;
$this->upload->initialize($config, true);
if (!$this->upload->do_upload($field)) {
return $default;
}
return base_url() . "assets/images/" . $this->upload->data('file_name');
}
Hi I am trying to import an CSV into MYSQL database using A CI Library. But I get this error in Controller that file type is now allowed
Controller:
<?php
class Csv extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('csv_model');
$this->load->library('csvimport');
}
function index() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$this->load->view('csvindex', $data);
}
function importcsv() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'phone'=>$row['phone'],
'email'=>$row['email'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
/*END OF FILE*/
The Model :
<?php
class Csv_model extends CI_Model {
function __construct() {
parent::__construct();
}
function get_addressbook() {
$query = $this->db->get('addressbook');
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return FALSE;
}
}
function insert_csv($data) {
$this->db->insert('addressbook', $data);
}
}
/*END OF FILE*/
I am trying to Import A CSV using PHP Codeigniter. Now I am getting an error that
The filetype you are attempting to upload is not allowed.
So as you can see i have kept the allowed file type = csv then also this issue is coming. So please help. Thanks
Instead of changing the mime type you can go with the CALLBACK function
This will add more portability too...
function importcsv() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$data['error'] = ''; //initialize image upload error array to empty
$this->form_validation->set_rules('uploaded_file','Uploaded file', 'trim|callback_chk_attachment');
if($this->form_validation->run()){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'phone'=>$row['phone'],
'email'=>$row['email'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
Call Back function for File Upload validation:
public function chk_attachment() // callback validation for check the attachment extension
{
$file_type = array('.csv');
if(!empty($_FILES['uploaded_file']['name']))
{
$ext = strtolower(strrchr($_FILES['uploaded_file']['name'],"."));
if(in_array($ext,$ext_array))
{
return true;
}
else
{
$this->form_validation->set_message('chk_attachment','Attachment allowed only csv');
return false;
}
}
{
$this->form_validation->set_message('chk_attachment','image field is required');
return false;
}
}
In this, I want to upload csv files. Validation is not correct but without validation its working.
This is my controller:
public function uploadstatetype()
{
$config['upload_path'] = APPPATH.'/assets/upload/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '5000';
with = ' ';
$replace = '"';
$this->load->library('upload', $config);
$this->load->database();
if ( ! $this->upload->do_upload('file_name'))
{
$error = array('error' => $this->upload->display_errors());
$this->managestate($error);
}
else
{
//Insert file info into database
$data = array('upload_data' => $this->upload->data());
$userfile = $data['upload_data']['file_name'];
$this->load->library('csvreader');
$upload_data = $this->upload->data();
$this->load->library('csvreader');
$file = $upload_data['full_path'];
$file_name = $upload_data['userfile'];
$data = $this->csvreader->parse_file($file);
foreach($data as $row)
{
if(($row['state_id']=='')||($row['state_name']==''))
{
$this->session->set_flashdata('msg_excel','Please check the details in the file, some details are empty.');
redirect(base_url().'admin/businesslocation/managestate');
}
else
{
$results_array = array(
'state_id' => $row['state_id'],
'state_name' => $row['state_name']
);
$this->load->model('admin/businesslocation_model');
$this->businesslocation_model->stateupload($results_array);
$success_message='Successfully Upload!';
$this->session->set_flashdata('success_message',$success_message);
redirect(base_url().'admin/businesslocation/managestate');
}
}
}
}
And this is my model:
function stateupload($results_array)
{
$this->db->insert('cr_state', $results_array);
}
For eg state_id=1 and state_name="kerala". Then insert is working,when condition is not checked. But when if condition is given it's not working.
Change your condition like this and try
if(empty($row['state_id'])||(empty($row['state_name']))){
I'm trying create a website using codeigniter. The structure that I use is only using view and controller. The model is directly in controller.
So, i got this error message:
Severity: Notice
Message: Undefined variable: view
Filename: template/default.php
Line Number: 146
And this is my code on controller (artikeladmin.php)
public function add()
{
if($this->input->post())
{
$judul = $this->input->post('judul');
$kategori_id = $this->input->post('kategori_id');
$tanggal = $this->input->post('tanggal');
$gambar = $this->input->post('gambar');
$published = $this->input->post('published');
$deskripsi = $this->input->post('deskripsi');
$config['upload_path'] ='assets/images/upload/';
$config['allowed_types'] ='jpeg|png|gif|jpg';
$config['max_size'] ='*';
$config['max_width'] ='*';
$config['max_height'] ='*';
$this->load->library('upload', $config);
if(!$this->upload->do_upload())
{
$data['error'] = array('error' =>$this->upload->display_errors());
$this->load->view('admin/template/default', $data);
}
else
{
$attr = $this->upload->data();
$args = array(
'gambar' => $attr['file_name'],
'kategori_id' => $kategori_id,
'judul' => $judul,
'published' => $published,
'tanggal' => $tanggal,
'deskripsi' => $deskripsi
);
$this->db->insert('artikel', $args);
$this->session->set_flashdata('message','Data berhasil disimpan');
redirect('artikeladmin');
}
}
$user = $this->session->userdata('myuser');
if(!isset($user) or empty($user))
redirect('login');
$sql = " SELECT * FROM kategori";
$query = $this->db->query($sql);
$kategori = $query->result_array();
$data['view'] = 'admin/add_article';
$data['kategori'] = $kategori;
$data['action'] = 'artikeladmin/add/';
$this->load->view('admin/template/default', $data);
}
And this is my view (template/default.php)
<div id="content" class="span10">
<?php $this->load->view($view); ?>
</div>
in my controller you can see that i have define variable view like this
$data['view'] = 'admin/add_article';
And im trying to add new variable like
$data['view'] = $data;
but the error still happen
If do_upload() fails it will load the view without the $view variable being set:
if(!$this->upload->do_upload())
{
$data['error'] = array('error' =>$this->upload->display_errors());
$this->load->view('admin/template/default', $data);
}
default.php looks for $view
<?php $this->load->view($view); ?>
and you get the Undefined variable error.
Try instantiating $view before any calls to default.php are made.
I'm trying to add a final field to my project that contains a URL of the files that have been uploaded, if anyone could point me in the write direction for extending my model ?
I have included my codeIgniter Model & Controller code.
controller:
class Canvas extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index() {
$vars = array();
//$this->load->library('ChromePhp');
//$this->ChromePhp->log('test');
//$this->ChromePhp->log($_SERVER);
// using labels
// foreach ($_SERVER as $key => $value) {
// $this->ChromePhp->log($key, $value);
// }
// warnings and errors
//$this->ChromePhp->warn('this is a warning');
//$this->ChromePhp->error('this is an error');
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$user = $vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
// user already set up. Show thank you page
if($user != 0 && sizeof($_POST)>0) {
$this->do_upload();
$this->iterate_profile ($vars['user'],false,$_POST);
$this->load->view('canvas',$vars);
} else {
// user not set, show welcome message
$this->load->view('canvas',$vars);
}
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '20048';
$config['max_width'] = '10624';
$config['max_height'] = '10268';
$config['file_name'] = date("Y_m_d H:i:s");
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
function thank_you() {
$this->load->view('thank_you',$vars);
}
function remove() {
$vars = array();
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
if($vars['user'] == 0) {
// user not set, redirect
redirect('/', 'refresh');
} else {
// user already set up. Remove
$this->load->model('Users_Model');
$this->Users_Model->remove($vars['user']);
}
$this->load->view('removed',$vars);
}
protected function iterate_profile ($user,$breadcrumb,$item) {
foreach($item as $key => $value) {
if(is_array($value)) {
$this->iterate_profile($user,$key,$value);
}
else {
if($breadcrumb) {
//echo '[' . $breadcrumb . '_' . $key . ']= ' . $value . ' <br />';
$key = $breadcrumb . '_' . $key;
}
if( ! $this->Users_Model->exists($user,$key)) {
// does not exist in the database, insert it
$this->Users_Model->add($user,$key,$value);
} else {
$this->Users_Model->update($user,$key,$value);
}
}
}
}
}
Model:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
I don't think the question is very clear. But to me it seems you need to store the image path in the db. Otherwise you will need to perform a read directory on the upload path and then do something with the images.