Saturday, October 22, 2016

Codeigniter Multiple Upload File

Please follow the steps below to upload images or other files. If an error occurs when trying to please comment below.

Step 1
Create database : db_tutorial
CREATE TABLE `tb_file` (
  `file_ID` int(11) NOT NULL,
  `file_name` varchar(100) NOT NULL,
  `file_size` varchar(50) NOT NULL
);
Step 2
Open file config.php in /application/config/config.php
$config['base_url'] = 'http://localhost/tutorial/';
Step 3
Open file autoload.php in /application/config/autoload.php
$autoload['libraries'] = array(
    'form_validation',
    'upload',
    'database'
);

$autoload['helper'] = array(
    'html',
    'url'
);
Step 4
Open file database.php in /application/config/database.php
$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'db_tutorial',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);
Step 5
Create new controller with name Welcome.php in /application/controllers/Welcome.php
<?php

class Welcome extends CI_Controller {
 
    var $data = array();
 
    function  __construct() {
        parent::__construct();
    }
    
    function index() {
        if ($this->input->post('file_submit') && !empty($_FILES['file_upload']['name'])) {
            $number_of_files = sizeof($_FILES['file_upload']['tmp_name']);
            $files = $_FILES['file_upload'];
   
            for ($i = 0; $i < $number_of_files; $i++) {
                if ($_FILES['file_upload']['error'][$i] != 0) {
                    $this->form_validation->set_message('file_upload', 'Couldn\'t upload the files');
                    return false;
                }
            }
   
            $config['upload_path'] = FCPATH.'uploads/';
            $config['allowed_types'] = 'jpg|jpeg|bmp|png|gif';
            $config['encrypt_name'] = true;
   
            for ($i = 0; $i < $number_of_files; $i++) {
                $_FILES['file_upload']['name'] = $files['name'][$i];
                $_FILES['file_upload']['type'] = $files['type'][$i];
  $_FILES['file_upload']['tmp_name'] = $files['tmp_name'][$i];
  $_FILES['file_upload']['error'] = $files['error'][$i];
  $_FILES['file_upload']['size'] = $files['size'][$i];
    
  $this->upload->initialize($config);
  if ($this->upload->do_upload('file_upload')) {
      $data = $this->upload->data();
                    chmod($data['full_path'], 0777);
     
                    // insert to database
                    $insert[$i]['file_name'] = $data['file_name'];
                    $insert[$i]['file_size'] = $data['file_size'];
                }
            }
            $this->db->insert_batch('tb_file', $insert);
        }
  
        $this->data = array(
            'query' => $this->db->get('tb_file')
        );
  
        $this->load->view('welcome_message', $this->data);
    }
}
Step 6
Create new view file with name welcome_message.php in /application/views/welcome_message.php
<html>
    <head>
        <title>Codeigniter Multiple Upload File</title>
    </head>
    <body>
        <?php
        echo form_open_multipart();
 echo form_upload(array(
     'multiple' => '',
         'name' => 'file_upload[]'
        ));
        echo form_error('file_upload');
        echo form_submit(array(
            'name' => 'file_submit',
            'value' => 'Upload File'
        ));
        echo form_close();
        ?>
        <ul>
        <?php
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $data) {
                echo '<li>';
                echo img(array(
                    'src' => 'uploads/'.$data->file_name
                ));
                echo '</li>';
            }
        } else {
            echo '<li>Image still empty</li>';
        }
        ?>
    </ul>
</body>
</html>
Step 7
Create new folder with name uploads in <project_name>/uploads

Monday, October 10, 2016

Codeigniter Simple CRUD [part 2] 1 of 4

To continue this discussion, please follow the advance previously.
  1. Integration Between CodeIgniter With Bootstrap Framework [part 1]
STEP 1
Open file autoload.php in /application/config/autoload.php
$autoload['libraries'] = array(
    'template',
    'form_validation',
    'session',
    'database'
);

$autoload['helper'] = array(
    'style',
    'url'
);
STEP 2
Open file menu.php in /application/views/content/menu.php
find these scripts
<div id="navbar" class="navbar-collapse collapse">
And then type like this more or less
<div id="navbar" class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">CRUD <span class="caret"></span></a>
            <ul class="dropdown-menu">
                <li>
                    <?php echo anchor('welcome/crud/simple', 'Simple');?>
                </li>
            </ul>
        </li>
    </ul>
    <form class="navbar-form navbar-right">
        <div class="form-group">
            <input type="text" placeholder="Email" class="form-control">
        </div>
        <div class="form-group">
            <input type="password" placeholder="Password" class="form-control">
        </div>
        <button type="submit" class="btn btn-success">Sign in</button>
    </form>
</div>
STEP 3
Open file welcome.php in /application/controllers/Welcome.php
Add this function
public function crud($params = null) {
    if ($params == 'simple') {
        $this->_crud_simple();
    }
}

private function _crud_simple() {
    $validation = array(
        array('field' => 'first_name', 'rules' => 'required'),
        array('field' => 'last_name', 'rules' => 'required'),
        array('field' => 'age', 'rules' => 'required|numeric', 'label' => 'only between 1-9'),
        array('field' => 'street', 'rules' => 'required')
    );
    $this->form_validation->set_rules($validation);
    if ($this->form_validation->run() == true) {
        $this->submit->insert_simple_crud();
    }
            
    $this->data = array(
        'first_name' => set_value('first_name'),
        'last_name' => set_value('last_name'),
        'age' => set_value('age'),
        'street' => set_value('street')
    );
            
    $this->template->set('title', 'Simple CRUD');
    $this->template->load('main_template', 'content/simple_crud', $this->data);
}
And then find these scripts
public function __construct() {
And then type like this
public function __construct() {
    parent::__construct();
        
    $this->load->model('submit_model', 'submit', true);
}
STEP 4
Create new file with the name Submit_model.php and save in /application/models/Submit_model.php
<?php
class Submit_model extends CI_Model {

    function insert_simple_crud() {
        $this->db->insert('tb_bio', array(
            'first_name' => $this->input->post('first_name', true),
            'last_name' => $this->input->post('last_name', true),
            'age' => $this->input->post('age', true),
            'street' => $this->input->post('street', true)
        ));
        $this->session->set_flashdata('msg', '
            <p class="bg-primary" style="padding:10px">Success!</p>
        ');
        redirect('welcome/crud/simple');
    }

}
STEP 5
Create a database with names like the following example : appmurah_blog and this table script
CREATE TABLE `tb_bio` (
  `bio_ID` int(11) NOT NULL,
  `first_name` varchar(20) NOT NULL,
  `last_name` varchar(20) NOT NULL,
  `age` varchar(3) NOT NULL,
  `street` varchar(40) NOT NULL
);
STEP 6
Create new file with the name simple_crud.php save in /application/views/content/simple_crud.php
<div class="jumbotron">
    <div class="container">
        <h1>Simple CRUD!</h1>
    </div>
</div>
<div class="container">
    <div class="row">
    
        <?php echo form_open();?>
    
        <div class="col-md-12">
        
            <?php echo $this->session->flashdata('msg');?>
        
            <div class="form-group">
                <?php
                echo form_label('First Name', 'first_name');
                echo form_input(array(
                    'name' => 'first_name',
                    'id' => 'first_name',
                    'class' => 'form-control',
                    'value' => $first_name
                ));
                ?>
            </div>
            <div class="form-group">
                <?php
                echo form_label('Last Name', 'last_name');
                echo form_input(array(
                    'name' => 'last_name',
                    'id' => 'last_name',
                    'class' => 'form-control',
                    'value' => $last_name
                ));
                ?>
            </div>
            <div class="form-group">
                <?php
                echo form_label('Age', 'age');
                echo form_input(array(
                    'name' => 'age',
                    'id' => 'age',
                    'class' => 'form-control',
                    'value' => $age
                ));
                echo form_error('age');
                ?>
            </div>
            <div class="form-group">
                <?php
                echo form_label('Street', 'street');
                echo form_input(array(
                    'name' => 'street',
                    'id' => 'street',
                    'class' => 'form-control',
                    'value' => $street
                ));
                ?>
            </div>
            <div class="form-group">
                <?php
                echo form_submit(array(
                    'value' => 'Submit',
                    'class' => 'btn btn-primary'
                ));
                ?>            
            </div>
        </div>
        
        <?php echo form_close();?>
        
    </div>
</div>
Download this project

Wednesday, October 5, 2016

Integration Between CodeIgniter With Bootstrap Framework [part 1]

Please follow the steps below to upload images or other files. If an error occurs when trying to please comment below.

Step 1
Download bootstrap framework here.

Step 2
Open file config.php in /application/config/config.php
$config['base_url'] = 'http://localhost/appmurah_blog/';
Step 3
Open file routes.php in /application/config/routes.php
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = TRUE
Step 4
Create new file with name Welcome.php in /application/controllers/Welcome.php
<?php
class Welcome extends CI_Controller {

    var $data = array();

    public function __construct() {
        parent::__construct();
    }
    
    public function index() {
        $this->template->set('title', 'Dashboard');
        $this->template->load('main_template', 'content/dashboard', $this->data);
    }

}
if it is, then an error
Step 5
Create new file with name Template.php in /application/libraries/Template.php
<?php
class Template {

    var $template_data = array();

    public function __construct() {
        $this->CI = & get_instance();
    }

    public function set($name, $value) {
        $this->template_data[$name] = $value;
    }

    public function load($template = '', $view = '', $view_data = array(), $return = false) {
        $this->set('contents', $this->CI->load->view($view, $view_data, true));
        return $this->CI->load->view($template, $this->template_data, $return);
    }

    public function load_file($name) {
        return $this->CI->load->view($name);
    }

}
Step 6
Create new file with name style_helper.php in /application/helpers/style_helper.php
<?php
function css_tag($href = '', $type = 'text/css', $index_page = false) {
    $CI =& get_instance();
    
    $link = '';
    if (is_array($href)) {
        foreach ($href as $v) {
            $link .= css_tag($v, $type, $index_page);
        }
    } else {
        $link .= '<link ';
        if (strpos($href, '://') !== false) {
            $link .= 'href="'.$href.'"';
        } elseif ($index_page === true) {
            $link .= 'href="'.$CI->config->site_url($href).'"';
        } else {
            $link .= 'href="'.$CI->config->slash_item('base_url').$href.'"';
        }
        $link .= " type=\"{$type}\" rel=\"stylesheet\" />";
    }
    return $link;
}

function script_tag($src = '', $type = "text/javascript", $index_page = false) {
    $CI =& get_instance();
    
    $link = '';
    if (is_array($src)) {
        foreach ($src as $v) {
            $link .= script_tag($v, $type, $index_page);
        }
    } else {
        $link .= '<script ';
        if (strpos($src, '://') !== false) {
            $link .= 'src="'.$src.'"';
        } elseif ($index_page === true) {
            $link .= 'src="'.$CI->config->site_url($src).'"';
        } else {
            $link .= 'src="'.$CI->config->slash_item('base_url').$src.'"';
        }
        $link .= " type=\"{$type}\"></script>";
    }
    return $link;
}

function load_file($file) {
    $CI =& get_instance();
    
    return $CI->template->load_file($file);
}
Step 7
Open file autoload.php in /application/config/autoload.php
$autoload['libraries'] = array(
    'template'
);

$autoload['helper'] = array(
    'style'
);
Step 8
Create new folder with name content in /application/views/content
Step 9
Create new file with name main_template.php in /application/views/main_template.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title><?php echo $title;?></title>
    <?php
    echo css_tag('bootstrap/css/bootstrap.min.css');
    ?>
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
    <?php
    load_file('content/menu');
    echo $contents;
    echo script_tag('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js');
    echo script_tag('bootstrap/js/bootstrap.min.js');
    ?>
</body>
</html>
Step 10
Create new file with name menu.php in /application/views/content/menu.php
<nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <form class="navbar-form navbar-right">
                <div class="form-group">
                    <input type="text" placeholder="Email" class="form-control">
                </div>
                <div class="form-group">
                    <input type="password" placeholder="Password" class="form-control">
                </div>
                <button type="submit" class="btn btn-success">Sign in</button>
            </form>
        </div>
    </div>
</nav>
Step 11
Create new file with name dashboard.php in /application/views/content/dashboard.php
<div class="jumbotron">
    <div class="container">
        <h1>Hello, world!</h1>
        <p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
        <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more &raquo;</a></p>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-md-4">
            <h2>Heading</h2>
            <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
            <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
        </div>
        <div class="col-md-4">
            <h2>Heading</h2>
            <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
            <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
        </div>
        <div class="col-md-4">
            <h2>Heading</h2>
            <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
            <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
        </div>
    </div>
</div>

Tuesday, October 4, 2016

Codeigniter Image Upload

Please follow the steps below to upload images or other files. If an error occurs when trying to please comment below.

Step 1
Create database : db_test
CREATE TABLE IF NOT EXISTS `tb_image` (
    `image_ID` int(11) NOT NULL AUTO_INCREMENT,
    `file_name` varchar(100) NOT NULL,
    PRIMARY KEY (`image_ID`)
);

Step 2
Create controller file. /application/controller/image_upload.php
<?php
class Image_upload extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $config = array(
            'upload_path' => FCPATH.'upload/',
            'allowed_types' => 'jpg|jpeg|png|gif',
            'max_size' => 0,
            'file_name' => url_title($this->input->post('filename')),
            'encrypt_name' => true
        );
        $this->load->library('upload', $config);
        if ($this->upload->do_upload('filename')) {
            $this->db->insert('tb_image', array(
                'file_name' => $this->upload->filename
            ));
            if ($this->db->affected_rows() > 0) {
                $this->session->set_flashdata('msg', 'Image success uploaded.');
                redirect('image_upload');
            }
        }
        $data['result'] = $this->db->get('tb_image');
        $this->load->view('image_upload', $data);
    }

}

Step 3
Open file autoload.php. /application/config/autoload.php
<?php
$autoload['libraries'] = array(
    'database',
    'session',
    'form_validation'
);

$autoload['helper'] = array(
    'html',
    'url'
);

Step 4
Open file database.php. /application/config/database.php
<?php
$db['default'] = array(
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'db_test'
);

Step 5
Create view file. /application/views/image_upload.php
<html>
    <head>
        <title>Codeigniter Image Upload</title>
    </head>
    <body>
        <?php
        echo form_open_multipart();
        echo form_upload('filename');
        echo form_submit('upload', 'Upload');
        echo form_close();
        ?>
        <table width="100%">
            <tr>
                <th>&nbsp;</th>
                <th>FILENAME</th>
                <th>PATH</th>
            </tr>
            <?php
            if ($result->num_rows() > 0) {
                $i = 1;
                foreach ($result->result() as $data) {
                    echo '<tr>';
                    echo '<td>'.$i++.'</td>';
                    echo '<td>'.$data->file_name.'</td>';
                    echo '<td>'.img('upload/'.$data->file_name).'</td>';
                    echo '</tr>';
                }
            } else {
                echo '<tr>';
                echo '<td colspan="3">Empty</td>';
                echo '</tr>';
            }
            ?>
        </table>
    </body>
</html>

Step 6
Open file config.php. /application/config/config.php
<?php
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && ! in_array(strtolower($_SERVER['HTTPS']), array( 'off', 'no' ))) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/<your_project_name>';

Step 7
Open file routes.php. /application/config/routes.php
<?php
$route['default_controller'] = 'image_upload';

Step 8
Create folder : upload
<your_project_name>/upload