Jump to content

Moorcam

Members
  • Posts

    197
  • Joined

  • Last visited

Posts posted by Moorcam

  1. 14 hours ago, portabletelly said:

    So im trying to run a SQL query to insert data into a customer table. But I only want to insert date if the ID does not already exist.

    This code here works

    //************************************start of gizmola coe *************************
        $query = "INSERT INTO Customer (SyncroID, CompanyName) VALUES (?, ?)";
     
            try {
                $pdo->beginTransaction();
                $stmt = $pdo->prepare($query);
                    foreach ($customers as $customer)
                        {
                            if (!empty($customer['business_name'])) {
                            $stmt->execute([$customer['id'], $customer['business_name']]);
                                                                    }
                        }
            $pdo->commit();
                }
     
            catch (\Throwable $e){
                $pdo->rollback();
                throw $e;
                                 }
    //******************************end of gizmola code ***************************   

    However when I try to add the where clause in it just  bails out on the below code, im pretty sure my where statement has bad syntax and then im not sure the execute is done right?

      //**************https://forums.phpfreaks.com/topic/317537-curl-rate-limits-and-time-outs-limit-rate-under-a-certain-amount-for-get-requests/ *************************
      //updated syncroid  
      $query = "INSERT INTO Customer (SyncroID, CompanyName, Address, City, State, Postcode) VALUES (?, ?, ?, ?, ?, ?) WHERE (SyncroID) != VALUES (?)";
     
            try {
                $pdo->beginTransaction();
                $stmt = $pdo->prepare($query);
                    foreach ($customers as $customer)
                        {
                            if (!empty($customer['business_name'])) {
                                //udpated Customer ID for where clause
                                $stmt->execute([$customer['id'], $customer['business_name'], $customer['address'], $customer['city'], $customer['state'], $customer['zip'], [$customer['id']]);
                                                                    }
                        }
            $pdo->commit();
                }
     
            catch (\Throwable $e){
                $pdo->rollback();
                throw $e;
                                 }
    //******************************end of gizmola code *************************** 

     

    Only SELECT queries have WHERE clauses mate.

  2. On 11/24/2023 at 11:39 AM, gizmola said:

    This is not a panacea, but you could change the all_setting function to this:

     

    public function all_setting() {
        $query = $this->db->query("SELECT * from tbl_settings WHERE id=1 ORDER BY id");
        if ($query) {
            return $query->first_row('array');
        } else {
            return array();
        }
    }

     

    Then your modification would work.

    Thank you :)

  3. Hi guys,

    If my application is not installed, and you go to the main website, it throws the following error:

    Message: Call to a member function first_row() on bool

    Now, this is obviously because the database is empty.

    What I would like to do, instead of showing this error, I would like to automatically redirect to the install directory (if it exists).

    In Model_common, the following function is what is throwing the error:

        public function all_setting()
        {
            $query = $this->db->query("SELECT * from tbl_settings WHERE id=1 ORDER BY id");
            return $query->first_row('array');
        }

    I have tried this but to no avail in Home.php controller under function index

    		if (empty($data['setting'])) {
    			redirect('../install/');
    		}

    If anyone could help with this I would appreciate it.

    Cheers

    Dan

  4. Hi again all,

    Posting this for anyone who has experienced similar.

    It appears Codeigniter 3 has a bug that does not check for file extensions. Thus, not allowing certain files to be uploaded.

    The workaround is to create a piece of code that will do the checking for us  and allow for it to be uploaded.

    Here is that little piece of code:

                $ext = strtolower(pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION));
                if ($ext != "csv") {
                    // Not a CSV file - send error
                    $this->session->set_flashdata('error', 'Incorrect file extension uploaded. Only .CSV allowed!');
                    redirect("admin/csv");
                }

    Works a charm, thanks to my good friend Craig.

  5. Hi guys,

    I want to be able to dynamically change a site's color scheme using JS Colorpicker.

    I have the JS amd form etc all set and the color is updating in the database. However, I need to be able to use that database entry to change a color hex in a xss file.

    I am using Codeigniter 3

    Here is the HTML Form:

    <div class="tab-pane" id="color">
                                <?php echo form_open(base_url().'admin/setting/update',array('class' => 'form-horizontal')); ?>
                                <div class="box box-info">
                                    <div class="box-body">
                                        <div class="form-group">
                                            <label for="" class="col-sm-2 control-label">Color </label>
                                            <div class="col-sm-4">
                                                <input type="text" name="footer_bg" class="form-control jscolor" value="<?php echo $setting['footer_bg']; ?>">
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label for="" class="col-sm-2 control-label"></label>
                                            <div class="col-sm-6">
                                                <button type="submit" class="btn btn-success pull-left" name="form_color">Update</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php echo form_close(); ?>
                            </div>

    I have the following on the top of the style.php file:

    <?php
    header("Content-type: text/css");
    
    ?>

    This all works fine if I say have the following:

    <?php
    header("Content-type: text/css");
    $footer_bg = '#333';
    ?>
    
    background-color: <?php echo $footer_bg; ?>;

    However, if I try to call the color from settings database table it won't work.

    Can anyone help with this?

    Cheers,

    Dan

  6. Hi again folks,

    This really has me.

    I have changed to another method of importing, which includes uploading the file to the server and then reading it. Unfortunately, it isn't even uploading. Why? It baffles me as I have other uploads, such as images etc working just fine.

    Here is the controller now:

        function importcsv() {
            $data['fleet'] = $this->Model_fleet->show();
            $data['error'] = '';    //initialize image upload error array to empty
    
            $config['upload_path'] = './uploads/csv/';
            $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('admin/fleet', $data);
            } else {
                $file_data = $this->upload->data();
                $file_path =  $file_data['./uploads/csv/'];
                
                if ($this->Csvimport->get_array($file_path)) {
                    $csv_array = $this->Csvimport->get_array($file_path);
                    foreach ($csv_array as $row) {
                        $insert_data = array(
                            'v_number'=>$row['v_number'],
                            'v_eng_number'=>$row['v_eng_number'],
    						'v_vin'=>$row['v_vin'],
    						'v_chassis'=>$row['v_chassis'],
    						'v_make'=>$row['v_make'],
    						'v_model'=>$row['v_model'],
    						'v_height'=>$row['v_height'],
    						'v_length'=>$row['v_length'],
    						'v_width'=>$row['v_width'],
                            'v_reg'=>$row['v_reg'],
    						'v_pax'=>$row['v_pax'],
    						'tacho_number'=>$row['tacho_number'],
    						'service_date'=>$row['service_date'],
    						'v_notes'=>$row['v_notes'],
    						'status'=>$row['status'],
                        );
                        $this->Model_fleet->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('admin/fleet', $data);
                }
                
            } 
     

    Here is the Model:

        function insert_csv($data) {
            $this->db->insert('tbl_fleet', $data);
        }

    And the form (view):

    										<!-- Modal Start -->
    										<div class="modal fade" id="myModalDetail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    											<div class="modal-dialog" style="width:900px;">
    												<div class="modal-content">
    													<div class="modal-header">
    														<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    														<h4 class="modal-title" id="myModalLabel">
    															Import Fleet
    														</h4>
    													</div>
    													<div class="modal-body">
    														<div class="form-group">
    														<h3>Upload Fleet</h3>
    														<h4>From the options below, you can simply import your fleet quickly by uploading a spreadsheet/</h4>
    <label for="exampleInputFile">Upload Excel or CSV</label>
                    <?php echo form_open_multipart(base_url().'admin/fleet',array('class' => 'form-horizontal')); ?>
                        <input type="file" name="file" ><br><br>
                        <input type="submit" name="submit" value="UPLOAD" class="btn btn-primary">
                    <?php echo form_close(); ?>
    </div>
    													</div>
    												</div>
    											</div>
    										</div>
    
    										<!-- Modal End -->

    I am also using the csvimport Library as below, which is saved in libraries/Csvimport.php

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
    
    
    /**
     * CodeIgniter CSV Import Class
     *
     * This library will help import a CSV file into
     * an associative array.
     * 
     * This library treats the first row of a CSV file
     * as a column header row.
     * 
     *
     * @package         CodeIgniter
     * @subpackage      Libraries
     * @category        Libraries
     * @author          Brad Stinson
     */
    
    class Csvimport {
    
    	private $filepath = "";
        private $handle = "";
        private $column_headers = array();
    
       /**
         * Function that parses a CSV file and returns results
         * as an array.
         *
         * @access  public
         * @param   filepath        string  Location of the CSV file
         * @param   column_headers  array   Alternate values that will be used for array keys instead of first line of CSV
         * @param   detect_line_endings  boolean  When true sets the php INI settings to allow script to detect line endings. Needed for CSV files created on Macs.
         * @return  array
         */
        public function get_array($filepath='', $column_headers='', $detect_line_endings=FALSE)
        {
            global $column_headers;
            // If true, auto detect row endings
            if($detect_line_endings){
                ini_set("auto_detect_line_endings", TRUE);
            }
    
            // If file exists, set filepath
            if(file_exists($filepath))
            {
                $this->_set_filepath($filepath);
            }
            else
            {
                return FALSE;            
            }
    
            // If column headers provided, set them
            $this->_set_column_headers($column_headers);
    
            // Open the CSV for reading
            $this->_get_handle();
            
            $row = 0;
    
            while (($data = fgetcsv($this->handle, 0, ",")) !== FALSE) 
            {   
                // If first row, parse for column_headers
                if($row == 0)
                {
                    // If column_headers already provided, use them
                    if($this->column_headers)
                    {
                        foreach ($this->column_headers as $key => $value)
                        {
                            $column_headers[$key] = trim($value);
                        }
                    }
                    else // Parse first row for column_headers to use
                    {
                        foreach ($data as $key => $value)
                        {
                           $column_headers[$key] = trim($value);
    
                        }   
    
                    }          
                }
                else
                {
                    $new_row = $row - 1; // needed so that the returned array starts at 0 instead of 1
                    foreach($column_headers as $key => $value) // assumes there are as many columns as their are title columns
                    {
                        $result[$new_row][$value] = trim($data[$key]);
                    }
                }
                $row++;
            }
     
            $this->_close_csv();
    
            return $result;
        }
    
       /**
         * Sets the filepath of a given CSV file
         *
         * @access  private
         * @param   filepath    string  Location of the CSV file
         * @return  void
         */
        private function _set_filepath($filepath)
        {
            $this->filepath = $filepath;
        }
    
       /**
         * Sets the alternate column headers that will be used when creating the array
         *
         * @access  private
         * @param   column_headers  array   Alternate column_headers that will be used instead of first line of CSV
         * @return  void
         */
        private function _set_column_headers($column_headers='')
        {
            if(is_array($column_headers) && !empty($column_headers))
            {
                $this->column_headers = $column_headers;
            }
        }
    
       /**
         * Opens the CSV file for parsing
         *
         * @access  private
         * @return  void
         */
        private function _get_handle()
        {
            $this->handle = fopen($this->filepath, "r");
        }
    
       /**
         * Closes the CSV file when complete
         *
         * @access  private
         * @return  array
         */
        private function _close_csv()
        {
            fclose($this->handle);
        }    
    }

    If anyone can please provide any idea I would love you forever.

    There are no errors etc, just nothing happening.

    Cheers,

    Dan

  7. 1 hour ago, maxxd said:

    Where? You posted this:

    echo "<pre>"; print_r($this->Model_fleet->saverecords);

    This won't actually run the saverecords() method, and even if it did it's now passing no arguments instead of 15. Instead of passing all the individual properties of saverecords() to insert(), create an array of them and pass that to the db->insert() method.

    Before you do that, though, echo every row of the csv file to the browser to make sure your problem is with storage and not input. If the script can't find the input file it certainly won't be able to store the records to the database.

    Posted a few posts back, sorry.

        function saverecords($v_number,$v_eng_number,$v_vin,$v_chassis,$v_make,$v_model,$v_height,$v_length,$v_width,$v_reg,$v_pax,$tacho_number,$service_date,$v_notes,$status) 
    	{
            $this->db->insert('tbl_fleet',$v_number,$v_eng_number,$v_vin,$v_chassis,$v_make,$v_model,$v_height,$v_length,$v_width,$v_reg,$v_pax,$tacho_number,$service_date,$v_notes,$status);
            return $this->db->insert_id();
        }

     

    Anyway, I have tried the following. It shows no result at all.

    public function import_data(){
    	if(isset($_POST['file']))
    	{
        $csv = $_FILES['file']['tmp_name'];
        $handle = fopen($csv,"r");
        while (($row = fgetcsv($handle, 10000, ",")) != FALSE)
        {
            $num = count($data);
            echo "<p> $num fields in line $row: <br /></p>\n";
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo $data[$c] . "<br />\n";
            }
        }
        fclose($handle);
    }
    }

     

  8. 22 minutes ago, maxxd said:

    The other concern is that db->insert() takes two parameters - one string and one array - but you're passing 16 string parameters to it. That's one parameter that matches expected type, one parameter that doesn't match type, and 14 parameters that are ignored entirely.

    I have amended that in my last reply.

    I have tried other methods as well, uploading the file to /uploads/ and trying to read it from there. Can't even get the bloody thing to upload.

    I give up. Thanks anyway.

  9. 1 hour ago, maxxd said:

    From the documentation for db->insert:

    Have you tried catching the return value from the method and echoing it out during the loop? Or even just echoing the values on each loop so you know that you're dealing with what you think you're dealing with?

    I am running this just after the success set_flashdata:

    echo "<pre>"; print_r($this->Model_fleet->saverecords);

    Nothing

  10. 28 minutes ago, maxxd said:

    I kinda feel like you need to load the model and tell it to connect to the database before you try to do anything with it? I think the last time I worked with CI was like 3 years ago? It was slightly before the onset of covid, so I may be completely wrong.

    Don't think so. I am already updating, adding, deleting data from that same Model. I have also modified the Model code for the saverecords so it is similar to others I am using:

        function saverecords($v_number,$v_eng_number,$v_vin,$v_chassis,$v_make,$v_model,$v_height,$v_length,$v_width,$v_reg,$v_pax,$tacho_number,$service_date,$v_notes,$status) 
    	{
            $this->db->insert('tbl_fleet',$v_number,$v_eng_number,$v_vin,$v_chassis,$v_make,$v_model,$v_height,$v_length,$v_width,$v_reg,$v_pax,$tacho_number,$service_date,$v_notes,$status);
            return $this->db->insert_id();
        }

    My feeling is it is with the controller part posted below. I am just at a complete loss with it.

     

    	public function importdata()
    	{ 
    		$this->load->view('view_fleet');
    		if(isset($_POST["submit"]))
    		{
    			$file = $_FILES['file']['tmp_name'];
    			$handle = fopen($file, "r");
    			$c = 0;//
    			while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
    			{
    				$v_number = $filesop[0];
    				$v_eng_number = $filesop[1];
    				$v_vin = $filesop[2];
    				$v_chassis = $filesop[3];
    				$v_make = $filesop[4];
    				$v_model = $filesop[5];
    				$v_height = $filesop[6];
    				$v_length = $filesop[7];
    				$v_width = $filesop[8];
    				$v_reg = $filesop[9];
    				$v_pax = $filesop[10];
    				$tacho_number = $$filesop[11];
    				$service_date = $filesop[12];
    				$v_notes = $filesop[13];
    				$status = $filesop[14];
    				if($c<>0){					/* SKIP THE FIRST ROW */
    					$this->Model_fleet->saverecords(
    					$v_number,
    					$v_eng_number,
    					$v_vin,
    					$$v_chassis,
    					$v_make,
    					$v_model,
    					$v_height,
    					$v_length,
    					$v_width,
    					$v_reg,
    					$v_pax,
    					$tacho_number,
    					$service_date,
    					$v_notes,
    					$status
    					);
    				}
    				$c = $c + 1;
    			}
    			echo "sucessfully import data !";
    			
    				
    		}else{
    		    	$this->session->set_flashdata('error',$error);
    		    	redirect(base_url().'admin/fleet/edit/'.$id);
    		}
    	}

     

  11. 18 minutes ago, maxxd said:

    It's been a few years since I used CodeIgniter, but it certainly looks like you're passing 15 parameters (one of which is a dynamic variable) to a method that accepts 2 parameters. If you try to dump anything other than $v_number or $v_reg from your save_records() method, what do you get?

    Same thing.

    I also sorted the 15 against the 2 variables (missed that) and also still the same.

  12. Hi guys,

    Trying to implement an import function in Codeigniter 3 but not working.

    There are no errors, just get this screen:

    An Error Was Encountered

    The action you have requested is not allowed.

    Here is the Controller part:

    	public function importdata()
    	{ 
    		$this->load->view('view_fleet');
    		if(isset($_POST["submit"]))
    		{
    			$file = $_FILES['file']['tmp_name'];
    			$handle = fopen($file, "r");
    			$c = 0;//
    			while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
    			{
    				$v_number = $filesop[0];
    				$v_eng_number = $filesop[1];
    				$v_vin = $filesop[2];
    				$v_chassis = $filesop[3];
    				$v_make = $filesop[4];
    				$v_model = $filesop[5];
    				$v_height = $filesop[6];
    				$v_length = $filesop[7];
    				$v_width = $filesop[8];
    				$v_reg = $filesop[9];
    				$v_pax = $filesop[10];
    				$tacho_number = $$filesop[11];
    				$service_date = $filesop[12];
    				$v_notes = $filesop[13];
    				$status = $filesop[14];
    				if($c<>0){					/* SKIP THE FIRST ROW */
    					$this->Model_fleet->saverecords(
    					$v_number,
    					$v_eng_number,
    					$v_vin,
    					$$v_chassis,
    					$v_make,
    					$v_model,
    					$v_height,
    					$v_length,
    					$v_width,
    					$v_reg,
    					$v_pax,
    					$tacho_number,
    					$service_date,
    					$v_notes,
    					$status
    					);
    				}
    				$c = $c + 1;
    			}
    			echo "sucessfully import data !";
    				
    		}
    	}

    Now the Model part:

    	function saverecords($v_number,$v_reg)
    	{
    		$query="insert into tbl_fleet values('$v_number','$v_eng_number','$v_vin','$v_chassis','$v_make','$v_model','$v_height','$v_length','$v_width','$v_reg','$v_pax','$tacho_number','$service_date','$v_notes,$status')";
    		$this->db->query($query);
    	}

    And finally the View part:

    <label for="exampleInputFile">Upload Excel or CSV</label>
    <form enctype="multipart/form-data" method="post" role="form">
    <div class="form-group">
    <input type="file" name="file" id="file" size="150">
    <p class="help-block">Only Excel/CSV File Import.</p>
    </div>
    <button type="submit" class="btn btn-default" name="submit" value="submit">Upload</button>
    </form>
    </div>

    Please note that the View section is infact in a Modal. Not sure if that's the issue?

     

    If anyone can help with this I will send you some Guinness.

    Thanks.

  13. If anyone else wants this, here's what solved it for me...

    document.getElementById("printButton1").addEventListener("click", function() {
         var printContents = document.getElementById('invoice').innerHTML;
         var originalContents = document.body.innerHTML;
    	 var printButton = document.getElementById("printButton1");
    	 var closeButton = document.getElementById("closeButton1");
    	 
         document.body.innerHTML = printContents;
    	 
    document.getElementById('printButton1').style.visibility = 'hidden';
         window.print();
    
         document.body.innerHTML = originalContents;
    
    	 window.location.reload(true);
    });

     

  14. I have changed the above code and tried this, adding a link to the CSS file of the website...

    function printDiv() 
    {
    
      var divToPrint=document.getElementById('invoice');
      var newWin=window.open('','Print-Window');
      var cssURL='<?php echo base_url('public/css/style.css'); ?>';
    var printButton = document.getElementById("printButton1");
    var closeButton = document.getElementById("closeButton1");
    
      newWin.document.open();
    printButton.style.visibility = 'hidden';
    closeButton.style.visibility = 'hidden';
      newWin.document.write('<html><head><link href="'+cssURL+'" rel="stylesheet" type="text/css"></head><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
     printButton.style.visibility = 'visible';
     closeButton.style.visibility = 'visible';
      newWin.document.close();
    
      setTimeout(function(){newWin.close();},10);
    
    }

    Still not getting any styling in the print dialog.

  15. Hi folks,

    I am using the following JS to print the contents of a Div. However, when I click on Print, the print preview window opens but the document has no styling.

    function printDiv() 
    {
    
      var divToPrint=document.getElementById('invoice');
    
      var newWin=window.open('','Print-Window');
    
    var printButton = document.getElementById("printButton1");
    var closeButton = document.getElementById("closeButton1");
    
      newWin.document.open();
    printButton.style.visibility = 'hidden';
    closeButton.style.visibility = 'hidden';
      newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
     printButton.style.visibility = 'visible';
     closeButton.style.visibility = 'visible';
      newWin.document.close();
    
      setTimeout(function(){newWin.close();},10);
    
    
    }

    Button for printing:

    <input type="button" id="printButton1" class="btn btn-success" onclick="printDiv('invoice')" value="Print Invoice" />

    Is there something wrong here or am I just missing something?

    Cheers,

    Dan

  16. 38 minutes ago, maxxd said:

    It's been a while since I've used CodeIgniter - especially an older version - but I don't see where you've loaded the URL helper. Check here for more information.

    Hey man,

    Yeah it's in the Controller:

               

    			$this->load->view('traveller/view_testimonial_add',$data);

    Yeah I'm still learning it. Went for an older version because I was told it's easier. It is but this has me stumped.

  17. Hi all,

    Hope you are all well and Happy New Year. ;)

    Now, I have pulled hair out with this since last night. When I click on Add Testimonial it should open traveller/testimonial/add, which has a file name of view_traveller_testimonial_add.php

     

    But, when I click on the button to add a new Testimonial, it doesn't work. Just refreshed the page.

    Any ideas?

     

    Here is this file:

    <section class="content-header">
    	<div class="content-header-left">
    		<h1>Add Testimonial</h1>
    	</div>
    	<div class="content-header-right">
    		<a href="<?php echo base_url(); ?>traveller/testimonial" class="btn btn-primary btn-sm">View All</a>
    	</div>
    </section>
    
    
    <section class="content">
    
    	<div class="row">
    		<div class="col-md-12">
    
    			<?php
    			if($this->session->flashdata('error')) {
    				?>
    				<div class="callout callout-danger">
    					<p><?php echo $this->session->flashdata('error'); ?></p>
    				</div>
    				<?php
    			}
    			if($this->session->flashdata('success')) {
    				?>
    				<div class="callout callout-success">
    					<p><?php echo $this->session->flashdata('success'); ?></p>
    				</div>
    				<?php
    			}
    			?>
    
    	<?php echo form_open_multipart(base_url().'traveller/testimonial/add',array('class' => 'form-horizontal')); ?>
    				<div class="box box-info">
    					<div class="box-body">
    						<div class="form-group">
    							<label for="" class="col-sm-2 control-label">Name <span>*</span></label>
    							<div class="col-sm-6">
    								<input type="text" class="form-control" name="name" value="<?php echo $d_arr['traveller_name']; ?>">
    							</div>
    						</div>
    						<div class="form-group">
    							<label for="" class="col-sm-2 control-label">Website</label>
    							<div class="col-sm-6">
    								<input type="url" autocomplete="off" class="form-control" name="url" value="">
    							</div>
    						</div>				
    						<div class="form-group">
    							<label for="" class="col-sm-2 control-label">Comment <span>*</span></label>
    							<div class="col-sm-6">
    								<textarea class="form-control" name="comment" style="height:200px;"></textarea>
    							</div>
    						</div>
    
    							<div class="col-sm-6" hidden>
    							<label for="" class="col-sm-2 control-label">Status</label>
    								<input type="text" autocomplete="off" class="form-control" name="status" value="Pending">
    							</div>
    						</div>
    						<div class="form-group">
    							<label for="" class="col-sm-2 control-label"></label>
    							<div class="col-sm-6">
    								<button type="submit" class="btn btn-success pull-left" name="form1">Submit</button>
    							</div>
    						</div>
    					</div>
    				</div>
    			<?php echo form_close(); ?>
    		</div>
    	</div>
    
    </section>

    Here is the file that has the button to open the above page:

    <div class="dashboard-area bg-area pt_50 pb_80">
    	<div class="container wow fadeIn">
    		<div class="row">
    			<div class="col-md-3 col-sm-12 wow fadeIn" data-wow-delay="0.1s">
    				<div class="option-board mt_30">
    					<ul>
    						<?php $this->view('view_traveller_sidebar'); ?>
    					</ul>
    				</div>
    			</div>
    			<div class="col-md-9 col-sm-12 wow fadeIn" data-wow-delay="0.2s">
    				<div class="box-body table-responsive">
    
    					<h1>My Testimonials</h1>
    					<table id="example1" class="table table-bordered table-striped">
    						<thead>
    							<tr>
    								<th>Serial</th>
    								<th>Name</th>
    								<th>Comment</th>
    							</tr>
    						</thead>
    						<tbody>
    							<?php
    							$i=0;
    							foreach ($my_testimonial as $row) {
    								$i++;
    
    								$CI =& get_instance();
    								$CI->load->model('Model_testimonial');
    								$CI->load->model('Model_traveller');
    								$d_arr = $CI->Model_traveller->get_traveller_name_by_id($row['traveller_id']);
    								
    
    								?>
    								<tr>
    									<td><?php echo $i; ?></td>
    									<td><?php echo $d_arr['traveller_name']; ?></td>
    									<td><?php echo $row['comment']; ?></td>
    								</tr>
    								<?php
    							}
    							?>
    							
    						</tbody>
    					</table>
    					<div class="box-body">
    					<a href="<?php echo base_url(); ?>traveller/testimonial/add" class="btn btn-primary btn-sm">Add Testimonial</a>
    					</div>
    				</div>
    			</div>
    		</div>
    	</div>
    </div>

    Here is my Controller:

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Testimonial extends CI_Controller 
    {
    	function __construct() 
    	{
            parent::__construct();
            $this->load->model('traveller/Model_common');
            $this->load->model('traveller/Model_testimonial');
        }
    
    	public function index()
    	{
    		$data['setting'] = $this->Model_common->get_setting_data();
    
    		$data['testimonial'] = $this->Model_testimonial->show();
    
    		$this->load->view('traveller/view_header',$data);
    		$this->load->view('traveller/view_testimonial',$data);
    		$this->load->view('traveller/view_footer');
    	}
    
    	public function add()
    	{
    		$data['setting'] = $this->Model_common->get_setting_data();
    
    		$error = '';
    		$success = '';
    
    		if(isset($_POST['form1'])) {
    
    			$valid = 1;
    
    			$this->form_validation->set_rules('name', 'Name', 'trim|required');
    			$this->form_validation->set_rules('comment', 'Comment', 'trim|required');
    
    			if($this->form_validation->run() == FALSE) {
    				$valid = 0;
                    $error .= validation_errors();
                }
    
    
    		    if($valid == 1) 
    		    {
    				$next_id = $this->Model_testimonial->get_auto_increment_id();
    				foreach ($next_id as $row) {
    		            $ai_id = $row['Auto_increment'];
    		        }
    
    		        $form_data = array(
    					'name'        => $_POST['name'],
    					'url' => $_POST['url'],
    					'status' => $_POST['status'],
    					'comment'     => $_POST['comment']
    	            );
    	            $this->Model_testimonial->add($form_data);
    
    		        $success = 'Testimonial is added successfully!';
    		        $this->session->set_flashdata('success',$success);
    				redirect(base_url().'traveller/testimonial');
    		    } 
    		    else
    		    {
    		    	$this->session->set_flashdata('error',$error);
    				redirect(base_url().'traveller/testimonial/add');
    		    }
                
            } else {
                
                $this->load->view('traveller/view_header',$data);
    			$this->load->view('traveller/view_testimonial_add',$data);
    			$this->load->view('traveller/view_footer');
            }
    		
    	}
    
    
    	public function edit($id)
    	{
    		
        	// If there is no testimonial in this id, then redirect
        	$tot = $this->Model_testimonial->testimonial_check($id);
        	if(!$tot) {
        		redirect(base_url().'traveller/testimonial');
            	exit;
        	}
           	
           	$data['setting'] = $this->Model_common->get_setting_data();
    		$error = '';
    		$success = '';
    
    
    		if(isset($_POST['form1'])) 
    		{
    
    			$valid = 1;
    
    			$this->form_validation->set_rules('name', 'Name', 'trim|required');
    			$this->form_validation->set_rules('comment', 'Comment', 'trim|required');
    
    			if($this->form_validation->run() == FALSE) {
    				$valid = 0;
                    $error .= validation_errors();
                }
    
    		    if($valid == 1) 
    		    {
    		    	$data['testimonial'] = $this->Model_testimonial->get_testimonial($id);
    			$form_data = array(
    						'name'        => $_POST['name'],
    						'url' => $_POST['url'],
    						'status' => $_POST['status'],
    						'comment'     => $_POST['comment']
    		            );
    					$this->Model_testimonial->update($id,$form_data);
    				
    				$success = 'Testimonial is updated successfully';
    				$this->session->set_flashdata('success',$success);
    				redirect(base_url().'traveller/testimonial');
    		    }
    		    else
    		    {
    		    	$this->session->set_flashdata('error',$error);
    				redirect(base_url().'traveller/testimonial/edit'.$id);
    		    }
               
    		} else {
    			$data['testimonial'] = $this->Model_testimonial->get_testimonial($id);
    	       	$this->load->view('traveller/view_header',$data);
    			$this->load->view('traveller/view_testimonial_edit',$data);
    			$this->load->view('traveller/view_footer');
    		}
    
    	}
    
    
    	public function delete($id) 
    	{
    		// If there is no testimonial in this id, then redirect
        	$tot = $this->Model_testimonial->testimonial_check($id);
        	if(!$tot) {
        		redirect(base_url().'traveller/testimonial');
            	exit;
        	}
    
            $data['testimonial'] = $this->Model_testimonial->get_testimonial($id);
            if($data['testimonial']) {
                unlink('./public/uploads/'.$data['testimonial']['photo']);
            }
    
            $this->Model_testimonial->delete($id);
            $success = 'Testimonial is deleted successfully';
    		$this->session->set_flashdata('success',$success);
            redirect(base_url().'traveller/testimonial');
        }
    
    }

    And my Model:

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Model_testimonial extends CI_Model 
    {
    
    	function get_auto_increment_id()
        {
            $sql = "SHOW TABLE STATUS LIKE 'tbl_testimonial'";
            $query = $this->db->query($sql);
            return $query->result_array();
        }
    	
        function show() {
            $sql = "SELECT * FROM tbl_testimonial ORDER BY id ASC";
            $query = $this->db->query($sql);
            return $query->result_array();
        }
    
        function add($data) {
            $this->db->insert('tbl_testimonial',$data);
            return $this->db->insert_id();
        }
    
        function update($id,$data) {
            $this->db->where('id',$id);
            $this->db->update('tbl_testimonial',$data);
        }
    
        function delete($id)
        {
            $this->db->where('id',$id);
            $this->db->delete('tbl_testimonial');
        }
    
        function get_testimonial($id)
        {
            $sql = 'SELECT * FROM tbl_testimonial WHERE id=?';
            $query = $this->db->query($sql,array($id));
            return $query->first_row('array');
        }
    
        function testimonial_check($id)
        {
            $sql = 'SELECT * FROM tbl_testimonial WHERE id=?';
            $query = $this->db->query($sql,array($id));
            return $query->first_row('array');
        }
        
    }

    Really appreciate the help guys. Thanks in advance.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.