My $data array is not getting passed to the view per the code and errors shown below.
public function myAccount(){
$data = array(
'templateVersion' => 'template1',
'headerVersion' => 'header2',
'css' => '',
'navBarVersion' => 'navBar2',
'main_content' => 'myaccount/myAccount',
'page_title' => 'example.com - My Account',
'footerVersion' => 'footer2'
);
if (($this->session->userdata('is_logged_in')) == 1) {
$config['upload_path'] = $this->logo_path;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ($this->input->post('upload')) {
if(!$this->upload->do_upload('userfile')){
echo $this->upload->display_errors('<p>', '</p>');
} else {
$w = $this->upload->data();
$data = array(
'field_input_name' => $w['file_name'],
);
//$this->db->insert('table_image', $data);
echo "here";
//exit;
}
}
//******************************************
// For some reason, $data is not passed in!
// Have posted the web screen error far below.
$this->load->view('includes/template1', $data);
}else{
redirect('site/restricted');
}
}
////////////////////////////////////////////////////////////////////
A PHP Error was encountered Severity: Notice Message: Undefined
variable: headerVersion Filename: includes/template1.php Line
Number: 4
An Error Was Encountered
Unable to load the requested file: includes/.php
You have initialised $data twice. Once in the beginning of the function and again in else condition of upload.Inside else condition of upload change like this
$data['field_input_name'] = $w['file_name'];
It will work.
$data array's keys are converted into variables
$data['someKey'] = array(
'templateVersion' => 'template1',
'headerVersion' => 'header2',
'css' => '',
'navBarVersion' => 'navBar2',
'main_content' => 'myaccount/myAccount',
'page_title' => 'example.com - My Account',
'footerVersion' => 'footer2'
);
In view you can access as print_r($someKey);
use die(var_dump($someKeys)); in view to see results
As you are trying to upload images in CI you can use
echo $this->image_lib->display_errors(); for some other error detection or debugging
Related
I have tried all solutions but I can't tell what's wrong. Codeigniter keeps telling me that there's no file uploaded. I created the folder at the root of the project. I've seen other similar questions but I can't manage to make it work with their solutions.
This is my controller:
public function index() {
$this->form_validation->set_rules('name', 'name', 'required|trim|max_length[45]');
$this->form_validation->set_rules('type_id', 'type', 'required|trim|max_length[11]');
$this->form_validation->set_rules('stock', 'stock', 'required|trim|is_numeric|max_length[11]');
$this->form_validation->set_rules('price', 'price', 'required|trim|is_numeric');
$this->form_validation->set_rules('code', 'code', 'required|trim|max_length[45]');
$this->form_validation->set_rules('description', 'description', 'required|trim|max_length[45]');
$this->form_validation->set_rules('active', 'active', 'required|trim|max_length[45]');
$this->form_validation->set_rules('unit_id', 'unit', 'required|trim|max_length[45]');
$this->form_validation->set_rules('userfile', 'File', 'trim');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
$this->load->view('product/add_view');
} else { // passed validation proceed to post success logic
// build array for the model
$form_data = array(
'name' => set_value('name'),
'type_id' => set_value('type_id'),
'stock' => set_value('stock'),
'price' => set_value('price'),
'code' => set_value('code'),
'description' => set_value('description'),
'active' => set_value('active'),
'unit_id' => set_value('unit_id')
);
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
$this->upload->initialize($config); //Make this line must be here.
$imagen = set_value('userfile');
// run insert model to write data to db
if ($this->product_model->product_insert($form_data) == TRUE) { // the information has therefore been successfully saved in the db
if (!$this->upload->do_upload($imagen)) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('product/add_view', $error);
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('product/add_view', $data);
}
} else {
redirect('products/AddProduct', 'refresh');
// Or whatever error handling is necessary
}
}
}
This is my view (just showing the part that matters)
<?php // Change the css classes to suit your needs
$attributes = array('class' => '', 'id' => '');
echo form_open_multipart('products/AddProduct', $attributes); ?>
<p>
<label for="picture">Picture <span class="required">*</span></label>
<?php echo form_error('userfile'); ?>
<?php echo form_upload('userfile')?>
<br/>
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
EDIT: Applying the modification from the answer I get an error 500.
I tried to work on your code. and it worked on me after this changes
$config = array(
'upload_path' => "./uploads/",
'upload_url' => base_url()."uploads/", // base_url()."/uploads/", //added
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload'); //changed
$this->upload->initialize($config); //Make this line must be here.
$imagen = userfile; // $_FILES['userfile']['name'] //changed
If you get The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500 possible error on your syntax, I just add 1 more } at the end of your code. You can check phpinfo() for other information. Also, there might be a problem on your file locations maybe the address you specified or the permissions if your running this on server.
I made insert data along upload images into the database , when the run was successful , but when the insert data and upload images contained errors.
The path to the image is not correct.
Your server does not support the GD function required to process this type of image.
how to cope if I insert the data without uploading images is not error ? and the image database went into default image ?
This my controllers
public function save(){
$this->load->library('image_lib');
//$nama_asli = $_FILES['userfile']['name'];
$id = $this->input->post('id',TRUE);
$config['file_name'] = $id ;//'_'.'_'.$nama_asli;
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
$config['max_size'] = '100000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$files = $this->upload->data();
$fileNameResize = $config['upload_path'].$config['file_name'];
$size = array(
array('name' => 'thumb','width' => 100, 'height' => 100, 'quality' => '100%')
);
$resize = array();
foreach($size as $r){
$resize = array(
"width" => $r['width'],
"height" => $r['height'],
"quality" => $r['quality'],
"source_image" => $fileNameResize,
"new_image" => $url.$r['name'].'/'.$config['file_name']
);
$this->image_lib->initialize($resize);
if(!$this->image_lib->resize())
die($this->image_lib->display_errors());
}
}
else
{
$data = array('upload_data' => $this->upload->data());
$get_name = $this->upload->data();
$nama_foto = $get_name['file_name'];
$this->mcrud->savealat($nama_foto);
redirect('instrument/detailalat');
}
}
This my model
function savealat($nama_foto) {
$data = array(
'id' => $this->input->post('id'),
'namaalat' => $this->input->post('namaalat'),
'dayalistrik' => $this->input->post('dayalistrik'),
'merk' => $this->input->post('merk'),
'namasupplier' => $this->input->post('namasupplier'),
'nokatalog' => $this->input->post('nokatalog'),
'noseri' => $this->input->post('noseri'),
'category' => $this->input->post('category'),
'lokasi' => $this->input->post('lokasi'),
'pengguna' => $this->input->post('pengguna'),
'status' => $this->input->post('status'),
'jadwalkal' => $this->input->post('jadwalkal'),
'manual' => $this->input->post('manual'),
'dateinput' => $this->input->post('date'),
'foto' => $nama_foto
//'created' => $tanggal
);
$this->db->insert('tbdetail', $data);
}
public function save(){
$this->load->library('image_lib');
//$nama_asli = $_FILES['userfile']['name'];
$id = $this->input->post('id',TRUE);
$config['file_name'] = $id ;//'_'.'_'.$nama_asli;
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
$config['max_size'] = '100000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$files = $this->upload->data();
$fileNameResize = $config['upload_path'].$config['file_name'];
$size = array(
array('name' => 'thumb','width' => 100, 'height' => 100, 'quality' => '100%')
);
$resize = array();
foreach($size as $r){
$resize = array(
"width" => $r['width'],
"height" => $r['height'],
"quality" => $r['quality'],
"source_image" => $fileNameResize,
"new_image" => base_url().$r['name'].'/'.$config['file_name']
);
$this->image_lib->initialize($resize);
if(!$this->image_lib->resize())
die($this->image_lib->display_errors());
}
$data = array('upload_data' => $this->upload->data());
$get_name = $this->upload->data();
$nama_foto = $get_name['file_name'];
$this->mcrud->savealat($nama_foto);
redirect('instrument/detailalat');
}
else
{
//Moved your code up there
}
}
If I'm right the problem is that you put the upload in else. Try to move the code and tell me if it works
MaY be this answer can help you out. There are few more suggestion in comment part which can figure some way out for you. Your server does not support the GD function required to process this type of image.Ci
Here is my controller insertion code
This code inserts image into image path folder but the path is not saving in database.
function add_hotel() {
//validate form input
$this->form_validation->set_rules('hotelname', 'Hotel Name', 'required|xss_clean');
$this->form_validation->set_rules('hotellocation', 'Hotel Location', 'required|xss_clean');
$this->form_validation->set_rules('hotelphone', 'Hotel Phone', 'required|xss_clean');
$this->form_validation->set_rules('hotelimg', 'Hotel Image ', 'callback__image_upload');
$this->form_validation->set_rules('hotelabout', 'Hotel About', 'required|xss_clean');
if ($this->form_validation->run() == true)
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000000';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
$field_name = "hotelimg";
if ( ! $this->upload->do_upload($field_name))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/add_hotel', $error);
}
else {
$data = array(
'hotelname' => $this->input->post('hotelname'),
'hotellocation' => $this->input->post('hotellocation'),
'hotelphone' => $this->input->post('hotelphone'),
'hotelimg' => $this->upload->data('hotelimg'),
'hotelabout' => $this->input->post('hotelabout')
);
print_r($data);
$this->db->insert('hotel_content', $data);
$this->session->set_flashdata('message', "<p>Hotel added successfully.</p>");
redirect(base_url().'index.php/admin/hotel_controller/index');
}
Error shown is:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: mysql/mysql_driver.php
Line Number: 552
and
A Database Error Occurred:
Error Number: 1054
Unknown column 'Array' in 'field list'
INSERT INTO `hotel_content` (`hotelname`, `hotellocation`, `hotelphone`, `hotelimg`, `hotelabout`) VALUES ('hotel5', 'hyd', '0402365477', Array, 'welcome')
Filename: G:\wamp\www\CodeIgniter\system\database\DB_driver.php
Line Number: 330
I need path to be inserted in database. Can anyone help me?
replace else part with
else {
$data = array(
'hotelname' => $this->input->post('hotelname'),
'hotellocation' => $this->input->post('hotellocation'),
'hotelphone' => $this->input->post('hotelphone'),
'hotelimg' => $this->upload->data('hotelimg'),
'hotelabout' => $this->input->post('hotelabout')
);
print_r($data);
$this->db->insert('hotel_content', $data);
$this->session->set_flashdata('message', "<p>Hotel added successfully.</p>");
redirect(base_url().'index.php/admin/hotel_controller/index');
}
with this
else {
$image_path = $this->upload->data();
$data = array(
'hotelname' => $this->input->post('hotelname'),
'hotellocation' => $this->input->post('hotellocation'),
'hotelphone' => $this->input->post('hotelphone'),
'hotelimg' => $image_path[full_path],
'hotelabout' => $this->input->post('hotelabout')
);
print_r($data);
$this->db->insert('hotel_content', $data);
$this->session->set_flashdata('message', "<p>Hotel added successfully.</p>");
redirect(base_url().'index.php/admin/hotel_controller/index');
}
the line "$this->upload->data('hotelimg')" in else part returns an array.
You just need uploaded path from it which can be extracted as:
$temp = $this->upload->data('hotelimg');
$uploadedPath = $temp[full_path];
I have two controllers:
test.php
public function trackback()
{
$this->load->library('trackback');
$tb_data = array(
'ping_url' => 'http://www.citest.com/addtrackback/receive/777',
'url' => 'http://www.citest.com/test/trackback/',
'title' => 'Заголовок',
'excerpt' => 'Текст.',
'blog_name' => 'Название блога',
'charset' => 'utf-8'
);
if ( ! $this->trackback->send($tb_data))
{
echo $this->trackback->display_errors();
}
else
{
echo 'Trackback успешно отправлен!';
}
}
function trackback() sends the trackback information
addtrackback.php
public function receive()
{
$this->load->library('trackback');
if ($this->uri->segment(3) == FALSE)
{
$this->trackback->send_error("Не указан ID записи ");
}
if ( ! $this->trackback->receive())
{
$this->trackback->send_error("Trackback содержит некорректные данные!");
}
$data = array(
'tb_id' => '',
'entry_id' => $this->uri->segment(3),
'url' => $this->trackback->data('url'),
'title' => $this->trackback->data('title'),
'excerpt' => $this->trackback->data('excerpt'),
'blog_name' => $this->trackback->data('blog_name'),
'tb_date' => time(),
'ip_address' => $this->input->ip_address()
);
$sql = $this->db->insert_string('trackbacks', $data);
$this->db->query($sql);
$this->trackback->send_success();
}
function receive() gets trackback and writes it into a table called 'trackbacks' in the database.
But when I try to view the page, it results in the following error:
An unknown error was encountered.
What's causing this error?
are you referencing the library or the function you're in? if ( ! $this->trackback->send($tb_data))
try changing it to something like
public function trackback(){
$this->load->library('trackbackLibrary');
what are you trying to accomplish because it seems like you're attempting to do an if statement for the same process.
if ($this->uri->segment(3) == FALSE)
{
$this->trackback->send_error("Не указан ID записи ");
}
if ( ! $this->trackback->receive())
{
$this->trackback->send_error("Trackback содержит некорректные данные!");
}
Also,
Check your error_log file to see what the actual error its throwing. /var/log or some other places. Depending on your OS
Ok, that sounds really confusing. What I’m trying to do is this. I’ve got a function that uploads/resizes photos to the server. It stores the paths in the DB. I need to attach the id of the business to the row of photos.
Here’s what I have so far:
function get_bus_id() {
$userid = $this->tank_auth->get_user_id();
$this->db->select('b.id');
$this->db->from ('business AS b');
$this->db->where ('b.userid', $userid);
$query = $this->db->get();
if ($query->num_rows() > 0) {
// RESULT ARRAY RETURN A MULTIDIMENSIONAL ARRAY e.g. ARRAY OF DB RECORDS
// ( ROWS ), SO IT DOENS'T FIT
//return $query->result_array();
// THE CORRECT METHOD IS row_array(), THAT RETURN THE FIRST ROW OF THE
// RECORDSET
$query->row_array();
}
That get’s the id of the business. Then, I have my upload function which is below:
/* Uploads images to the site and adds to the database. */
function do_upload() {
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->gallery_path,
'max_size' => 2000
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->gallery_path . '/thumbs',
'maintain_ratio' => true,
'width' => 150,
'height' => 100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$upload = $this->upload->data();
$bus_id = $this->get_bus_id();
$data = array(
'userid' => $this->tank_auth->get_user_id(),
'thumb' => $this->gallery_path . '/thumbs/' . $upload['file_name'],
'fullsize' => $upload['full_path'],
'busid'=> $bus_id['id'],
);
echo var_dump($bus_id);
$this->db->insert('photos', $data);
}
The problem I’m getting is the following:
A PHP Error was encountered
Severity: Notice
Message: Undefined index: id
Filename: models/gallery_model.php
Line Number: 48
I’ve tried all sorts of ways to get the value over, but my limited knowledge keeps getting in the way. Any help would be really appreciated.
not sure how to ask you a question without submitting an "answer"...
what's in line 48? which file is gallery_model.php? from the sounds of it, it could be an array key that hasn't been initialized or an issue in querying the database.
The problem is that if the business is not found, your function is not returning anything. As a result, $bus_id has nothing in it (its not even an array). You should probably have your get_bus_id() function return false like so:
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
then after you call get_bus_id() you can check if $bus_id == false and maybe return false to denote an error from do_upload()
Ok, I have it working. This is the complete and working code:
/* Uploads images to the site and adds to the database. */
function do_upload() {
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->gallery_path,
'max_size' => 2000
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->gallery_path . '/thumbs',
'maintain_ratio' => true,
'width' => 150,
'height' => 100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$upload = $this->upload->data();
$bus_id = $this->get_bus_id();
/*
TABLE STRUCTURE =============
id, the row ID
photoname
thumb
fullsize
busid
userid
*/
$data = array(
'id' => 0 , // I GUESS IS AUTO_INCREMENT
'photoname' => '',
'thumb' => $this->gallery_path . '/thumbs/' . $upload['file_name'],
'fullsize' => $upload['full_path'],
'busid'=> $bus_id['id'],
'userid' => $this->tank_auth->get_user_id(),
);
// CHECK THE DATA CREATED FOR INSERT
$this->db->insert('photos', $data);
}
// Get Business ID from DB
function get_bus_id() {
$userid = $this->tank_auth->get_user_id();
$this->db->select('b.id');
$this->db->from ('business AS b');
$this->db->where ('b.userid', $userid);
$query = $this->db->get();
if ($query->num_rows() > 0) {
// RESULT ARRAY RETURN A MULTIDIMENSIONAL ARRAY e.g. ARRAY OF DB RECORDS
// ( ROWS ), SO IT DOENS'T FIT
//return $query->result_array();
// THE CORRECT METHOD IS row_array(), THAT RETURN THE FIRST ROW OF THE
// RECORDSET
return $query->row_array();
}
}