Saturday, December 29, 2018

How to find out where a function is defined?

You could also do this in PHP itself:

$reflFunc = new ReflectionFunction('function_name');

print $reflFunc->getFileName() . ':' . $reflFunc->getStartLine();


For Class methods you can use $reflFunc = new ReflectionMethod($this, 'method_name');

Tuesday, December 25, 2018

Laravel - Eloquent “Has”, “With”, “WhereHas” - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
 Note also that while with('relation') will include the related table's data in the returned collection, has('relation') and whereHas('relation') will not include the related table's data. So you may need to call both with('relation') as well as has() or whereHas().

Note: This article is taken from: https://stackoverflow.com/questions/30231862/laravel-eloquent-has-with-wherehas-what-do-they-mean

Thursday, December 20, 2018

Bootstrap/jquery click to show multiple hidden rows in a table

Accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:

HTML:

<table class="table table-condensed" style="border-collapse:collapse;">
    <thead>
        <tr>
            <th>#</th>
            <th>Date</th>
            <th>Description</th>
            <th>Credit</th>
            <th>Debit</th>
            <th>Balance</th>
        </tr>
    </thead>
    <tbody>
        <tr data-toggle="collapse" data-target=".demo1">
            <td>1</td>
            <td>05 May 2013</td>
            <td>Credit Account</td>
            <td class="text-success">$150.00</td>
            <td class="text-error"></td>
            <td class="text-success">$150.00</td>
        </tr>
        <tr>
            <td class="hiddenRow">
                <div class="collapse demo1">Demo1</div>
            </td>
            <td class="hiddenRow">
                <div class="collapse demo1">Demo1</div>
            </td>
            <td class="hiddenRow">
                <div class="collapse demo1">Demo1</div>
            </td>
            <td class="hiddenRow">
                <div class="collapse demo1">Demo1</div>
            </td>
            <td class="hiddenRow">
                <div class="collapse demo1">Demo1</div>
            </td>
            <td class="hiddenRow">
                <div class="collapse demo1">Demo1</div>
            </td>
        </tr>
        <tr data-toggle="collapse" data-target="#demo2">
            <td>2</td>
            <td>05 May 2013</td>
            <td>Credit Account</td>
            <td class="text-success">$11.00</td>
            <td class="text-error"></td>
            <td class="text-success">$161.00</td>
        </tr>
        <tr>
            <td colspan="6" class="hiddenRow">
                <div id="demo2" class="collapse">Demo2</div>
            </td>
        </tr>
        <tr data-toggle="collapse" data-target="#demo3">
            <td>3</td>
            <td>05 May 2013</td>
            <td>Credit Account</td>
            <td class="text-success">$500.00</td>
            <td class="text-error"></td>
            <td class="text-success">$661.00</td>
        </tr>
        <tr>
            <td colspan="6" class="hiddenRow">
                <div id="demo3" class="collapse">Demo3</div>
            </td>
        </tr>
    </tbody>

</table>

JQUERY:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');

});

JS Fiddle: http://jsfiddle.net/QLfMU/116/

Credits goes to: https://stackoverflow.com/users/4186945/hackel

Orginal Posted answer by Hackel: https://stackoverflow.com/questions/16389775/twitter-bootstrap-use-collapse-js-on-table-cells-almost-done


Wednesday, December 12, 2018

Upload Multiple Images and Store in Database using PHP and MySQL

File Upload in PHP is the most used functionality for the web application. Single file or multiple files can be easily uploaded using PHP. PHP provides a quick and simple way to implement server-side file upload functionality. Generally, in the web application, the file is uploaded to the server and the file name is stored in the database. Later the files are retrieved from the server based on the file name stored in the database.
Most cases, a single image is uploaded at once. But sometimes you have a requirement to upload multiple images at once. In this tutorial, we will show you how to upload multiple images in PHP and store the images in the MySQL database. Multiple image upload allows the user to select multiple files at once and upload all files to the server in a single click.
Our example code will implement the following functionality to demonstrate the multiple images upload in PHP.
  • HTML form to select multiple images.
  • Upload images to the server using PHP.
  • Store file names in the database using PHP and MySQL.
  • Retrieve images from the database and display on the web page.

Create Database Table

A table needs to be created in the database to store the image file names. The following SQL creates an imagestable with some basic fields in the MySQL database.
CREATE TABLE `images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the MySQL database. Specify the database hostname ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your MySQL credentials.
<?php// Database configuration$dbHost     "localhost";$dbUsername "root";$dbPassword "root";$dbName     "codexworld";
// Create database connection$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);
// Check connectionif ($db->connect_error) {
    die("Connection failed: " $db->connect_error);
}?>

File Upload Form HTML

Create an HTML form with an input field to allow the user to select images they want to upload.
The <form> tag must contain the following attributes.
  • method="post"
  • enctype="multipart/form-data"
The <input> tag must contain type="file" and multiple attributes.
<form action="" method="post" enctype="multipart/form-data">
    Select Image Files to Upload:
    <input type="file" name="files[]" multiple >
    <input type="submit" name="submit" value="UPLOAD">
</form>

Upload Multiple Files in PHP (upload.php)

The upload.php file handles the multiple image upload functionality and shows the upload status to the user.
  • Include the database configuration file to connect and select the MySQL database.
  • Get the file extension using pathinfo() function in PHP and check whether the user selects only the image files.
  • Upload images to the server using move_uploaded_file() function in PHP.
  • Insert image file names in the database using PHP and MySQL.
  • Show the upload status to the user.
<?phpif(isset($_POST['submit'])){
    // Include the database configuration file
    include_once 'dbConfig.php';
    
    // File upload configuration
    $targetDir "uploads/";
    $allowTypes = array('jpg','png','jpeg','gif');
    
    $statusMsg $errorMsg $insertValuesSQL $errorUpload $errorUploadType '';
    if(!empty(array_filter($_FILES['files']['name']))){
        foreach($_FILES['files']['name'] as $key=>$val){
            // File upload path
            $fileName basename($_FILES['files']['name'][$key]);
            $targetFilePath $targetDir $fileName;
            
            // Check whether file type is valid
            $fileType pathinfo($targetFilePath,PATHINFO_EXTENSION);
            if(in_array($fileType$allowTypes)){
                // Upload file to server
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){
                    // Image db insert sql
                    $insertValuesSQL .= "('".$fileName."', NOW()),";
                }else{
                    $errorUpload .= $_FILES['files']['name'][$key].', ';
                }
            }else{
                $errorUploadType .= $_FILES['files']['name'][$key].', ';
            }
        }
        
        if(!empty($insertValuesSQL)){
            $insertValuesSQL trim($insertValuesSQL,',');
            // Insert image file name into database
            $insert $db->query("INSERT INTO images (file_name, uploaded_on) VALUES $insertValuesSQL");
            if($insert){
                $errorUpload = !empty($errorUpload)?'Upload Error: '.$errorUpload:'';
                $errorUploadType = !empty($errorUploadType)?'File Type Error: '.$errorUploadType:'';
                $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType;
                $statusMsg "Files are uploaded successfully.".$errorMsg;
            }else{
                $statusMsg "Sorry, there was an error uploading your file.";
            }
        }
    }else{
        $statusMsg 'Please select a file to upload.';
    }
    
    // Display status message
    echo $statusMsg;
}?>

Display Images from Database

Now we will retrieve the file names from the database and display the respective images from the server on the web page.
  • Include the database configuration file to connect and select the MySQL database.
  • Fetch images from MySQL database using PHP.
  • Retrieve images from the server (uploads/) and listed on the web page.
<?php// Include the database configuration fileinclude_once 'dbConfig.php';
// Get images from the database$query $db->query("SELECT * FROM images ORDER BY id DESC");

if($query->num_rows 0){
    while($row $query->fetch_assoc()){
        $imageURL 'uploads/'.$row["file_name"];?>
    <img src="<?php echo $imageURL?>" alt="" />
<?php }
}else{ ?>    <p>No image(s) found...</p>
<?php ?> 



Upload Multiple Files and Images in CodeIgniter

 For CodeIgniter web application, you can use system library to implement file upload functionality. It will help you to upload file to the server in CodeIgniter.
CodeIgniter’s File Uploading Class allows files to be uploaded to the server. You can upload file or image easily using Upload library in CodeIgniter. Not only single file, but also the multiple files can be uploaded with CodeIgniter Upload library. In this tutorial, we will show you how to upload multiple files and images at once using CodeIgniter’s Upload Library.
In the example code, the following functionality will be implemented to demonstrate multiple files upload in CodeIgniter.
  • Create an HTML form to select multiple images at once.
  • Upload images to the server using CodeIgniter’s Upload library.
  • Store file data in the MySQL database.
  • Retrieve images from the database and display on the web page.

reate Database Table

To store the file name and related information, a table needs to be created in the database. The following SQL creates a files table in the MySQL database.
CREATE TABLE `files` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Create File Upload Folder

Create a directory on the server where you want to store the uploaded files. For example, create a uploads/files/directory in the root folder of the application.
codeigniter-multiple-files-upload-tutorial-create-upload-folder-codexworld

Controller (Upload_files.php)

The Upload_Files controller contains 2 functions, __construct() and index().
  • __construct() –
    • Loads SESSION library to show the uploading status to user.
    • Loads File model that helps to insert file data into the database and get files data from the database.
  • index() – This function handles the multiple file upload functionality.
    • Set preferences (upload path, allowed types, etc) and initialize Upload library.
    • Upload images to the server using Upload library.
    • Insert images data in the database using File model.
    • Get all images data from the database.
    • Pass the data to the view.
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Upload_Files extends CI_Controller {
    function  __construct() {
        parent::__construct();
        // Load session library
        $this->load->library('session');
        
        // Load file model
        $this->load->model('file');
    }
    
    function index(){
        $data = array();
        // If file upload form submitted
        if($this->input->post('fileSubmit') && !empty($_FILES['files']['name'])){
            $filesCount count($_FILES['files']['name']);
            for($i 0$i $filesCount$i++){
                $_FILES['file']['name']     = $_FILES['files']['name'][$i];
                $_FILES['file']['type']     = $_FILES['files']['type'][$i];
                $_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
                $_FILES['file']['error']     = $_FILES['files']['error'][$i];
                $_FILES['file']['size']     = $_FILES['files']['size'][$i];
                
                // File upload configuration
                $uploadPath 'uploads/files/';
                $config['upload_path'] = $uploadPath;
                $config['allowed_types'] = 'jpg|jpeg|png|gif';
                
                // Load and initialize upload library
                $this->load->library('upload'$config);
                $this->upload->initialize($config);
                
                // Upload file to server
                if($this->upload->do_upload('file')){
                    // Uploaded file data
                    $fileData $this->upload->data();
                    $uploadData[$i]['file_name'] = $fileData['file_name'];
                    $uploadData[$i]['uploaded_on'] = date("Y-m-d H:i:s");
                }
            }
            
            if(!empty($uploadData)){
                // Insert files data into the database
                $insert $this->file->insert($uploadData);
                
                // Upload status message
                $statusMsg $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
                $this->session->set_flashdata('statusMsg',$statusMsg);
            }
        }
        
        // Get files data from the database
        $data['files'] = $this->file->getRows();
        
        // Pass the files data to view
        $this->load->view('upload_files/index'$data);
    }

}

Model (File.php)

The File model contains 3 functions, __construct(), getRows() and insert().
  • __construct() – Define table name where the files data will be stored.
  • getRows() – Fetch the file data from the files table of the database. Returns a single record if ID is specified, otherwise all records.
  • insert() – Insert multiple files data into the database using insert_batch() function of Query Builder Class.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class File extends CI_Model{
    function __construct() {
        $this->tableName 'files';
    }
    
    /*
     * Fetch files data from the database
     * @param id returns a single record if specified, otherwise all records
     */
    public function getRows($id ''){
        $this->db->select('id,file_name,uploaded_on');
        $this->db->from('files');
        if($id){
            $this->db->where('id',$id);
            $query $this->db->get();
            $result $query->row_array();
        }else{
            $this->db->order_by('uploaded_on','desc');
            $query $this->db->get();
            $result $query->result_array();
        }
        return !empty($result)?$result:false;
    }
    
    /*
     * Insert file data into the database
     * @param array the data for inserting into the table
     */
    public function insert($data = array()){
        $insert $this->db->insert_batch('files',$data);
        return $insert?true:false;
    }
    
}

View (upload_files/index.php)

Initially, an HTML form is displayed with file input to select multiple files. After the form submission, the data is posted to index() function of Upload_Files controller for uploading multiple images to the server.
<!-- display status message -->
<p><?php echo $this->session->flashdata('statusMsg'); ?></p>

<!-- file upload form -->
<form method="post" action="" enctype="multipart/form-data">
    <div class="form-group">
        <label>Choose Files</label>
        <input type="file" name="files[]" multiple/>
    </div>
    <div class="form-group">
        <input type="submit" name="fileSubmit" value="UPLOAD"/>
    </div>
</form>
Under the file upload form, the uploaded images names and retrieved from the database and display the respective images from the server in a gallery view.
<!-- display uploaded images -->
<div class="row">
    <ul class="gallery">
        <?php if(!empty($files)){ foreach($files as $file){ ?>
        <li class="item">
            <img src="<?php echo base_url('uploads/files/'.$file['file_name']); ?>" >
            <p>Uploaded On <?php echo date("j M Y",strtotime($file['uploaded_on'])); ?></p>
        </li>
        <?php } }else{ ?>
        <p>Image(s) not found.....</p>
        <?php ?>
    </ul>
</div>

Upload Class Preferences

In the example, some basic preferences are used for Upload library configuration ($config). But you can specify various preferences provided by the Upload Class in CodeIgniter.
  • upload_path – The path of the directory where the file will be uploaded. The path must be absolute and directory must be writable.
  • allowed_types – The mime types of the file that allows being uploaded.
  • file_name – If specified, the uploaded file will be renamed with this name.
  • file_ext_tolower – (TRUE/FALSE) If set to TRUE, file extension will be lower case.
  • overwrite – (TRUE/FALSE) TRUE – If a file exists with the same name, it will be overwritten. FALSE – If a file exists with the same name, a number will append to the filename.
  • max_size – (in kilobytes) The maximum size of the file that allowed to upload. Set to 0 for no limit.
  • max_width – (in pixels) The maximum width of the image that allowed to upload. Set to 0 for no limit.
  • max_height – (in pixels) The maximum height of the image that allowed to upload. Set to 0 for no limit.
  • min_width – (in pixels) The minimum width of the image that allowed to upload. Set to 0 for no limit.
  • min_height – (in pixels) The minimum height of the image that allowed to upload. Set to 0 for no limit.
  • max_filename – The maximum length of the file name. Set to 0 for no limit.

How to backup and download Database using PHP

< ?php $mysqlUserName = 'databaseusername' ; $mysqlPassword = 'databasepassword' ; $mysqlHostNa...