get recurring dates between two dates and periods php codeigniter

	public function getRecurringDates($start_date,$period,$weekdayNumbers = [])
	{
		$end_date = date("Y-m-d", strtotime("+$period days", strtotime($start_date)) );

	    $dateArr = array();

	    foreach ($weekdayNumbers as $key => $weekdayNumber) {


			$startDate = strtotime($start_date);
		    $endDate = strtotime($end_date);

	    	do
		    {
		        if(date("w", $startDate) != $weekdayNumber)
		        {
		            $startDate += (24 * 3600); // add 1 day
		        }
		    } while(date("w", $startDate) != $weekdayNumber);


		    while($startDate <= $endDate)
		    {
		        $dateArr[] = date('Y-m-d', $startDate);
		        $startDate += (7 * 24 * 3600); // add 7 days
		    }

	    }
		    
	    return($dateArr);
	}

        // die('lol');
	$event_id = (isset($_POST['event_id']))? $_POST['event_id'] : 331; 
	$start_date = (isset($_POST['event_start_date']))? $_POST['event_start_date'] : '2017-04-15';
	$period = (isset($_POST['event_period']))? $_POST['event_period'] : 60;
	$weekdayNumbers = (isset($_POST['event_id']) && is_array($_POST['event_id']))? $_POST['event_id'] : [0,2];

	$dateArr = $this->getRecurringDates($start_date, $period, $weekdayNumbers);
		

Advertisements

dublicate a child table rows and parent table rows mysql [CodeIgniter]


    // call to model to model ...
    public function duplicateTableRecord ($table, $keys = [],$ignore_key) 
    {
       /* generate the select query */
       if (is_array($keys)) {
           foreach ($keys as $key_field => $key_val) {

               $this->db->where($key_field, $key_val); 
           
           }
       }
       // return var_dump($keys);
       $query = $this->db->get($table);
      
        foreach ($query->result() as $row){   
           foreach($row as $key=>$val){        
              if($key != $ignore_key){ 
              /* $this->db->set can be used instead of passing a data array directly to the insert or update functions */
              $this->db->set($key, $val);               
              }//endif              
           }//endforeach
        }//endforeach

        /* insert the new record into table*/
        $this->db->insert($table); 
        return $this->db->insert_id();
    }

    public function duplicateForeignTableRecord ( $table, $foreign_keys_vals = [],$ignore_key,$update_keys_vals = [] ) 
    {
       /* generate the select query */
       if (is_array($foreign_keys_vals)) {
           foreach ($foreign_keys_vals as $key_field => $key_val) {

               $this->db->where($key_field, $key_val); 
           
           }
       }
       // $this->db->where($foreign_key_field, $foreign_key_val); 

       $query = $this->db->get($table);
      
        foreach ($query->result() as $row){   
           foreach($row as $key => $val){        
              if($key != $ignore_key){ 
              /* $this->db->set can be used instead of passing a data array directly to the insert or update functions */
                $this->db->set($key, $val);               
              }
              foreach ($update_keys_vals as $up_f_key => $up_f_val) {
                  if($key == $up_f_key){
                    $this->db->set($key, $up_f_val); 
                  }
              }
              //endif              
           }//endforeach

           $this->db->insert($table);
        
        }//endforeach

        /* insert the new record into table*/
         
        return $this->db->insert_id();
    }

    // call to function to from controller to model class. 
    public function clone_product($id)
    {
        $product_insert_id = $this->duplicateTableRecord(
            'product',
            ['id_product' => $id],
            'id_product'
        );

        $insert_id = $this->duplicateForeignTableRecord(
            'product_join_category',
            ['id_product' => $id],
            'id_product',
            [ 'id_product' => $product_insert_id ]
        );

        $insert_id = $this->duplicateForeignTableRecord(
            'product_data',
            ['id_product' => $id],
            'id_product_data',
            [ 'id_product' => $product_insert_id ]
        );
        
        $insert_id = $this->duplicateForeignTableRecord(
            'file',
            [ 'id_product' => $id ],
            'id_file',
            [ 'id_product' => $product_insert_id ]
        );
        
        $insert_id = $this->duplicateForeignTableRecord(
            'metatag',
            [ 'section_item_id' => $id, 'section' => 'product' ],
            'id_meta',
            [   'section_item_id' => $product_insert_id ]
        );

        return $product_insert_id;
    }

    // call to the model from controller 
    public function copy($id = '')
    {
        if ($id != '') {

            $record = $this->b_product_model->clone_product($id);
        
        }
        
        // _trace($record);
        redirect(base_url() . 'admin/produkty');
    }

[php] Breadcrumbs for Codeigniter in the helper function

function _breadcrumbs()
{
    $ci = & get_instance();
    $urlSegment = $ci->uri->segment_array();

    if (($key = array_search("product", $urlSegment)) !== false) {
        unset($urlSegment[$key]);
    }
    if (($key = array_search("products", $urlSegment)) !== false) {
        unset($urlSegment[$key]);
    }
    if (($key = array_search("product-category", $urlSegment)) !== false) {
        unset($urlSegment[$key]);
    }

    // print_r($urlSegment);

    $breadcrumbs = '<div class="row">
            <div class="col-sm-12">
                <p class="breadcrumb"><a href="" title=""><img src="' . base_url() .'assets/frontend/img/home.svg" alt="" /></a> ';

    foreach ($urlSegment as $key => $segment) {
        $breadcrumbs .= '<img src="'. base_url() .'assets/frontend/img/gt.png" alt="" /> '. ucfirst($segment) . ' ';
    }

    $breadcrumbs .= '</p>
            </div>
        </div>';

    echo $breadcrumbs;
}

Ajax Search PHP through MySQL record


var searchRequest = null;

$(function () {
    var minlength = 3;

    $("#spedostech_search").keyup(function () {
        var that = this,
        value = $(this).val();

        if (value.length >= minlength ) {
            if (searchRequest != null) 
                searchRequest.abort();

            console.log( );
            // return;
            
            searchRequest = $.ajax({
                type: "GET",
                url: BASE_URL + "spedostech/search",
                data: {
                    'search_keyword' : value
                },
                dataType: "json",
                success: function(msg){
                    // var obj = JSON.stringify(msg);
                    console.log(msg);
                    //we need to check if the value is the same
                    if (value==$(that).val()) {
                        var container = $('<ul />');
                        $.each( msg, function( section, List ) {
                          var li = $('<li>Nalezeno v '+section+' (3)</li>');

                          // container.append('<li>Nalezeno v '+section+' (3)</li>');
                          // console.log( section + " : ");
                          var ul = $('<ul />');
                          $.each( List, function( key, item ) {
                            ul.append('<li><a href="#'+item.id+'" title="">'+item.name+'</a></li>');
                            // console.log("Name : " + item.name);
                          });
                          li.append(ul);
                          container.append(li);  
                        });

                    // console.log(container);
                        // $('#tt').html(container);
                        $('#search-whisperer').html(container);

                    //Receiving the result of search here
                    }
                }
            });
        }
    });
});



MYSQL backup by command in php

add a xml file called database.xml and also folders sql/ and sql_zip/ and

add a php file call backupdb.php and paste this class snippet


	/**
	* Database Backup classed for all the db at once
	*/
	class DatabaseBackup
	{

		private $dbhost = '';
		private $dbuser = '';
		private $dbpass = '';

		public $connection = null;
		
		function __construct($dbhost = 'localhost',$dbuser = 'root',$dbpass = '')
		{
			$this->dbhost = $dbhost;
			$this->dbuser = $dbuser;
			$this->dbpass = $dbpass;

			$this->connection = mysqli_connect($this->dbhost, $this->dbuser ,$this->dbpass);

		}


		// export all single database recursively 
		public function exportAll($extract_type = 'sql', $path = 'sql/')
		{
			
			$res = mysqli_query($this->connection,"SHOW DATABASES");
			
			while ($row = mysqli_fetch_assoc($res)) {
			   
				$dbname = $row['Database'];   

				if($extract_type == 'zip'){
				 
				$backup_file = $dbname . date("Y-m-d-H-i-s") . '.sql.gz';
				$command = "mysqldump --opt 
							-h $this->dbhost 
							-u $this->dbuser $dbname 
							| gzip > sql_zip/$backup_file";

				system($command);
				}
				else {
					$backup_file = $dbname . date("Y-m-d-H-i-s") . '.sql';
				$command = "mysqldump --user=$this->dbuser --password=$this->dbpass --host=$this->dbhost $dbname  > sql/" . $backup_file;
				// return $command;

				exec($command);
				}



				$db[] = [

				 'filename' => $backup_file,
				 'dbname' 	=> $dbname

				];

				 
			}

			return $db;
		}

		// export all single database recursively and save log to xml
		public function dbToXMLRecord($file = null)
		{
			$dbs = $this->exportAll();

			$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><databases></databases>');

			$xml->addAttribute('version', '1.0');

			foreach ($dbs as $key => $db) {

				$item  =  $xml->addChild('item');
				$item->addChild('filename',$db['filename']);
				$item->addChild('dbname',$db['dbname']);

			
			}

			$databaseXML = fopen("databases.xml", "w") or die("Unable to open file!");
			
			fwrite($databaseXML, $xml->asXML());
			
			fclose($databaseXML);

			return $xml->asXML();
		
		}

		// import single db from xml recursively from xml file
		public function xmlToDBRecord($file = 'databases.xml')
		{
			$xmlDoc = new DOMDocument();
			$xmlDoc->load($file);
			$x = $xmlDoc->documentElement;

			$count = 1;

			foreach ($x->childNodes AS $items) {

				print_r($items->childNodes[1]->nodeValue);


				$res = mysqli_query($this->connection,"CREATE DATABASE IF NOT EXISTS ". $items->childNodes[1]->nodeValue);
				mysqli_query($this->connection,"USE ".$items->childNodes[1]->nodeValue);
				
				$command = "mysql -u $this->dbuser -p $this->dbpass < sql/". $items->childNodes[0]->nodeValue ;
				// return $res;

				exec($command,$output=array(),$worked);

				switch($worked){
				    case 0:
				        echo 'Import file <b>' .$items->childNodes[0]->nodeValue .'</b> successfully imported to database <b>' .$items->childNodes[1]->nodeValue .'</b>';
				        break;
				    case 1:
				        echo 'There was an error during import. Please make sure the import file is saved in the same folder as this script and check your values:<br/><br/><table><tr><td>MySQL Database Name:</td><td><b>' .$items->childNodes[1]->nodeValue .'</b></td></tr><tr><td>MySQL User Name:</td><td><b>' .$this->dbuser .'</b></td></tr><tr><td>MySQL Password:</td><td><b>NOTSHOWN</b></td></tr><tr><td>MySQL Host Name:</td><td><b>' .$this->dbhost .'</b></td></tr><tr><td>MySQL Import Filename:</td><td><b>' .$items->childNodes[0]->nodeValue .'</b></td></tr></table>';
				        break;
				}
				
				echo $command . "<br>";

				$count++;
								
			}

			return $count;
		}

		// test import 
		public function tryImport()
		{
			$command = "mysql -u $this->dbuser -p $this->dbpass < sql/music2017-02-02-23-21-12.sql" ;
            return $command;
            exec($command);
		}

		// all database in one sql file and xml
		public function tryAllExport()
		{
			// return $extract_type;
			$res = mysqli_query($this->connection,"SHOW DATABASES");
			// return $res;

			$databases = '';
			while ($row = mysqli_fetch_assoc($res)) {

				$databases .= $row['Database'] . ' ';
				
			}

			// return $databases;

			$command = "mysqldump -u $this->dbuser -p $this->dbpass --databases $databases > all_backup_2.sql" ;
			// $command = "mysqldump -u $this->dbuser -p $this->dbpass --databases c9db cashmemo clientapi db_lms > all_backup.sql" ;

			// return $command;

			$command = "mysqldump -u $this->dbuser -p $this->dbpass --all-databases > alldb_backup2.sql" ;
            
            // exec($command);
            exec('mysqldump -u root -p --all-databases --skip-lock-tables > alldb.sql');
		}



	}

	$dbBackup = new DatabaseBackup();

	if(isset($_GET['type']) && ($_GET['type'] == 'zip')){
		var_dump($dbBackup->exportAll('zip'));
	}
	else if(isset($_GET['to']) && ($_GET['to'] == 'xml')){
			var_dump($dbBackup->dbToXMLRecord());
	}
	else if(isset($_GET['to']) && ($_GET['to'] == 'db')){
			var_dump($dbBackup->xmlToDBRecord());
			// var_dump($dbBackup->tryImport());
	}
	else if(isset($_GET['to']) && ($_GET['to'] == 'tryx')){
			// var_dump($dbBackup->xmlToDBRecord());
			var_dump($dbBackup->tryAllExport());
	}
	else{
		var_dump($dbBackup->exportAll());
	}

in the browser serve “http://localhost/backupdb.php?to=xml
// here
to=xml for export from db to individuals sql file and xml enty
to=tryx all in a single file and also xml entry
to=zip all sqls file to zip in the sql_zip folder
to=db import from xml entry from sql files to db
record are saved as sql files in the sql folder and sql_zip folder