Showing posts with label codeigniter. Show all posts
Showing posts with label codeigniter. Show all posts

Friday, 4 March 2016

How to import csv file in mysql using codeigniter?

How to import CSV file into MySQL using Codeigniter?

The people have fear about something like new developer if he had not done some task he first thought that can I do it or not. Here I am telling you everything you do consistently and with patience then you will achieve the target. We explain you the things in simplest words so that you can get the idea how it works. Basically, for Codeigniter, I explain the example in three parts for import CSV file in MySQL using Codeigniter framework. Simple and easy way to work within the Codeigniter that is why the lot of developers working in Codeigniter.

1) View
2) Controller
3) Model

how to import csv file in mysql using codeigniter?

STEP ONE

View:

<form action ="" method="post">
 <input type="file" accept=".csv">
</form>

STEP TWO

Controller:

Import CSV library in controller
$this->load->library('csvimport');
Call model function.

STEP THREE

Model:

In model initialize configs and then load the upload library then initialize the config.
$config['upload_path'] = './assets/order_files/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '*';
$this->load->library('upload');
$this->upload->initialize($config);
// If upload failed, display error
if (!$this->upload->do_upload('upload')) {
     $data['error'] = $this->upload->display_errors();        
} else {
$file_data = $this->upload->data(); 
This line will hold all the information about the  file. like name, type, content type etc.
$file_path =  './assets/order_files/'.$file_data['file_name'];
$file_path =  './assets/order_files/'.$file_data['file_name'];
This will hold the file path
if ($this->csvimport->get_array($file_path))
{
    $csv_array = $this->csvimport->get_array($file_path);
    foreach ($csv_array as $row){       $insert_data = array(
        'firstName' => $row['fname'] ,
        'lastName' => $row['lname'],
        'Email' => $row['email'],
}
$q = $this->db->insert('table_Name', $csv_array);
How to import csv file in mysql using codeigniter

That's it. Simple and easy with Codeigniter. You can search with other search queries like import CSV file into MySQL in Codeigniter, Codeigniter CSV import library, CSV upload in Codeigniter, CSV import in Codeigniter example, Codeigniter import CSV file to database, how to import CSV file into database using PHP, Codeigniter export CSV file you get the other sites links for help also. If you have any query you can ask here in a comment box. I will response to your queries. You can further read about the image uploading that how you can upload the image on a server.
How to upload image in PHP...!

This Post Was Last Updated On September 30, 2016, By Author: Mahira Khan.

Tuesday, 16 February 2016

Different types of joins in mysql with examples

Different types of joins in MySQL with examples

Different types of joins in mysql with examples

Until now we have learned that how you can get data from one table by using MySQL queries or by Codeigniter queries just the syntax difference little bit but the concept is same. In real world scenario, you need to get data from multiple tables in a single SQL query. Joins are the concept that you retrieve data from multiple tables with minimum one thing same in both tables so that you can get the data from both tables. You can use either SELECT, UPDATE OR DELETE the data from multiple tables with one query. Simple join example is this:
$dbhost = 'localhost:8080';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$query = 'SELECT a.twotutorial_id, a.twotutorial_author, b.twotutorial_count
        FROM twotutorials_tbl a, twotcount_tbl b
        WHERE a.twotutorial_author = b.twotutorial_author';
mysql_select_db('TWOTUTORIAL');
$retval = mysql_query( $query, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
    echo "Author:{$row['twotutorial_author']}  <br> ".
         "Count: {$row['twotutorial_count']} <br> ".
         "Tutorial ID: {$row['twotutorial_id']} <br> ".
         "--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
There are basically five types of joins but the three of them are

INNER JOIN 

LEFT JOIN 

RIGHT JOIN



joins mysql

INNER JOIN

an inner join is a join that is used for the matching of the two rows with some comparison columns from two tables. The inner join will select all the data from both the tables that match.

Codeigniter syntax
simple/normal join
$this->db->select("*"):
$this->db->from("mytable");
$this->db->where(s.id=c.id)
$this->db->join("student", "student.id = course.id");
$query = $this->db->get();
MySQL syntax
select s.id, s.name, c.coursename
from student s
inner join course c
on s.id=c.id;

LEFT JOIN

Left join has just the little bit difference from the simple join that means simple join is working like inner join that select all the fields or write the fields that you only require. While left join has the simple little difference that you join the two tables with the same id or another field then it will only select all the columns from the left table and return to you. The simple syntax for left join is:
SELECT a.twotutorial_id, a.twotutorial_author, b.twotutorial_count
FROM twotutorials_tbl a LEFT JOIN twotcount_tbl b
ON a.twotutorial_author = b.twotutorial_author;

RIGHT JOIN

Left join has just the little bit difference from the simple join that means simple join is working like inner join that select all the fields or write the fields that you only require. While right join has the simple little difference that you join the two tables with the same id or another field then it will only select all the columns from the right table and return to you. The simple syntax for right join is:
SELECT a.twotutorial_id, a.twotutorial_author, b.twotutorial_count
FROM twotutorials_tbl a RIGHT JOIN twotcount_tbl b
ON a.twotutorial_author = b.twotutorial_author;
These are the same names you can search outpost by just typing types of joins in MySQL, different types of joins in MySQL with examples, joins in SQL, joins in MySQL PHP, joins in MySQL pdf, joins in MySQL tutorial pdf, joins in MySQL with example, joins in MySQL w3schools you will get the result. If you have still any query or problem you can ask in the comment box we will help you. You can further read about the reading the CSV files using Codeigniter.
Import CSV file using Codeigniter....!

This Post Was Last Updated On September 30, 2016, By Author: Mahira Khan.

Monday, 15 February 2016

Codeigniter Quries | php Quries

You can call with other names of the queries like PHP Codeigniter queries, Codeigniter joins query, Codeigniter 3 query, Codeigniter query string, Codeigniter query database, Codeigniter query string parameters, Codeigniter query result, Codeigniter query helper and many many other names. Codeigniter is the PHP framework that uses the pattern for database records. This pattern allows information to be retrieved, inserted and updated in your database with minimal scripting. Database connections are too easy to connect with database most of the things are already done in the framework we will show you that in later tutorials. This framework uses the pattern of MVC that means model, view, and controller. Codeigniter Queries | PHP Queries
We can use the crud by using the MVC method.

Codeigniter Quries | php Quries

  • Selecting Data
  • Inserting Data
  • Updating Data
  • Deleting Data

php Quries vs codeigniter quries

Select Data:

selecting data from multiple tables in MySQL, why choose MySQL, how to retrieve data from database in PHP using MySQL, PHP MySQL select, MySQL select where, how to display data from database in PHP, PHP MySQL query, how to fetch data from database in PHP and display in table are the same names of retrieving the data. In custom PHP, we create the MySQL query and execute that query same procedure in CodeIgniter is and we will create

CodeIgniter syntax
$query = $this->db->get("tableName");
php syntax/ mysql syntax
Select * from tableName;

we can also use the limit in the query like

CodeIgniter syntax
$query = $this->db->get("tableName", 10, 20);
php syntax/ mysql syntax
Select * from tableName limit 20, 10;

Insert Data

insert query example in MySQL, how to insert data in MySQL using PHP, how to insert data in Mysql using java, how to insert data in Mysql workbench, how to insert data in Mysql using JSP, how to insert data in MySQL using PHP form, how to insert data in Mysql using HTML form, how to insert data in MySQL using PHP Codeigniter are the same names you can call to insert data into the database. We can insert data in tables as the table fields are created  also with same data types. we  can insert an array of data or  just by putting numbers of data.

CodeIgniter syntax

$data = array(
  'title' => 'tableName,
  'name' => 'myname',
  'date' => 'mydate',
);
$this->db->insert('tableName', $data);
PHP syntax/ MySQL syntax
insert into tableName(title, content, date)values('mytitle', 'mycontent', 'mydate');
first parameter  elements are the table fields name and the seconds are the variables or values.

Updating Data

MySQL update syntax, how to update data in MySQL using java, how to update data in MySQL using PHP, MySQL update multiple columns, MySQL update select, MySQL update multiple rows, MySQL update join, update MySQL version these all are the same names you can call it. Updating data mean we already had entered the data and now we want to update that entered  data.

CodeIgniter syntax
$data = array(
               'title' => $title,
               'name' => $name,
               'date' => $date
            );
$this->db->where('id', $id);
$this->db->update('mytable', $data);

PHP syntax/ MySQL syntax
UPDATE my table
SET title = '{$title}', name = '{$name}', date = '{$date}'
WHERE id = $id;

Deleting Data

deleting data from MySQL database using PHP, how to remove duplicate data in MySQL, remove data from the MySQL table, MySQL remove column, MySQL removes primary key, MySQL removes all rows, remove me centos, remove me mac you can say it like this. Deleting data mean we are removing the entered data from our database so for this purpose we require the id or something like that to which we can compare and then delete the data.

CodeIgniter syntax
$this->db->delete('mytable', array('id' => $id));
PHP syntax/ MySQL syntax
DELETE FROM mytable
WHERE id = $id;
If you  people have any query about Codeigniter Queries | PHP Queries you can ask in the comment box. You can further read on the next stage it will increase your level of development.
You can Learn about the Joins between two or more tables....!

This Post Was Last Updated On September 30, 2016, By Author: Mahira Khan.

Thursday, 11 February 2016

How to create pagination in codigniter?

How to create pagination in CodeIgniter: First of all you must know what is pagination. Actually, pagination is the division of data into a number of pages.We divide the data into pages and each page can contain your own number of choice data to be displayed on each single page. Before the CodeIgniter pagination people have to manually create the things but now the CodeIgniter provide you lot of the things to do by just using the libraries of the framework. This is also the standard way where people work in the development field. Here we explain you the method how you can implement the pagination of CodeIgniter. We assume you know about the CodeIgniter controllers models and view that is MVC based framework, here is the controller where we set our logic to get the data from our database.

How to create pagination in codigniter

Controller

//pagination
First, load the pagination library by writing the code below it will load the functions that are going to be used after.

$this->load->library('pagination');

Configure the base URL that means the controller where you are displaying the data.

$config['base_url'] = "http://localhost/projects/helloworld/loginAdmin/";

Here we get the total number of results.

$total_records = $this->db->count_all('tablename');
$config['total_rows'] = $total_records;

Set the total number of results to show per page. Like here we set to display the 5 items per page on our website.

$config['per_page'] = 5;

Initialize the pagination.

$this->pagination->initialize($config);

Create the segments, segments are the number of pages that are written after the controller/function_name/segment_number understand the thing if now understand still tell us we will clear further in detail.

$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

this statement creates the links of base URL and displays the number of results.

$data['pagination'] = $this->pagination->create_links();

then send the data and execute the query.

$data['result'] = $this->crud_model->get_item($config['per_page'] ,$page);

load the view and send the query returned data.

$this->load->view('tableview', $data);

Model

In the model of CodeIgniter mod_pagination.php have the function which will get the database results that we need to show on each page for that we write a query.
public function get_item($page, $limit){
   $this->db->limit($page, $limit);
 $q = $this->db->get('testDb');     return $q->result();
}

View

In CodeIgniter, each and everything is being done like the pattern of MVC, model view and then controller so, here is the view. The page gets the variable from the controller and then we will display that in the pages.

<p class="text-center"><?php echo $pagination; ?></p>

How to create pagination in codigniter

This is the simple and easy way to do  or implement the pagination in the web application using CodeIgniter. People like to use the framework for their product development because of the fast and easy way to develop then compare to the custom language development. If you have any query in the pagination you can ask here the comment box. For further reading, you can view the CodeIgniter queries that will explain to you how you can write the database queries in an easy way using Codeigniter.
Codeigniter Queries or PHP Queries....!

This Post Was Last Updated On September 30, 2016, By Author: Mahira Khan.

How to create connectin with database in codeigniter?

How to create the connection with a database in Codeigniter: Connecting with the database in CodeIgniter is very easy you just need to enter few parameters in the database config file that create the connections with the database in CodeIgniter.  The basic parameters that you need to enter are.

How to create connectin with database in codeigniter?


  • Hostname
  • Username
  • Password
  • Database
What is hostname, username, password and database: The hostname is the server address that is the IP address and the hostname is assigned to that specific IP with a name is called hostname. The example in the local server name is localhost.  username of the server like in apache server by default user is the root user in local host and the password of the user root is nothing empty. The database you create in the localhost/PHPMyAdmin creates new database with the name you like to create that will be your database. These are the parameters that you must need to set for the database connections. Two syntaxes you can write in array

$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'mypassword',
'database' => 'datingSite',
'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
);
or you can also write like this
 $db['default']['hostname'] = 'localhost';
 $db['default']['username'] = 'root';
 $db['default']['password'] = 'mypass';
 $db['default']['database'] = 'datingSite';

How to create connectin with database in codeigniter?

Simple and easy to connect with database. For your information, you can connect multiple databases in one project application system. Like one database of "Employees" and other databases of "Passports," these two separate databases can be used at a time in one application system in software development process and it is a legal way, You can use it like this. If you have any problem you can ask here in the comment box We will response you. For further reading, you can read the pagination that is the next step.
How to create pagination in Codeigniter...!

This Post Was Last Updated On September 30, 2016, By Author: Mahira Khan.

Wednesday, 10 February 2016

How to upload images using codeigniter?

How to upload images using CodeIgniter: First create the HTML form in which you will make the field of type "file" and the form have attribute define the "enctype" of HTML form that is multipart/form-data and then the controller part that has the configs and also here we tell you about how to rename the file and save in the database of that file name.

How to upload images using codeigniter

upload picture HTML

<div class="row">
<div class="col-md-6">
<form method="post" action="<?php echo BURL; ?>/UserControl/uploadpicturefile" enctype="multipart/form-data">
<div class="form-group">
<label for="file">User Name</label>
<input type="file" name="file" class="form-control" id="file" placeholder="file">
</div>
<button type="submit" class="btn btn-default">Upload</button> </form>
</div>
</div>


Common Mistake: Here is the HTML part of the image upload that has one special attribute named enctype that is required for uploading the images you should use it otherwise you can not access the image file name.

upload picture login in PHP controller file.
public function uploadpicturefile(){
$id = $this->session->userdata('id');
    $config['upload_path'] = 'assets/user_images/';
$config['allowed_types'] ='*';
$config['max_size'] = '*';
$config['max_width']  = '*';
$config['max_height']  = '*';
$new_name = $id . $_FILES["file"]["name"];
$config['file_name'] = $new_name;
// insert new name of picture in signup table profileImage name
$this->Mod_user->insert_pic_name($id, $new_name);
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload('file'))
{
$status = 'error';
                       $msg = $this->upload->display_errors('<p>', '</p>');
                      echo $msg;
}else{
$data = array('file_uploaded' => $this->upload->data());
print_r($data);
echo 'else';
redirect(BURL. '/UserControl/userprofile');
}
 }
How to upload images using codeigniter

I hope you know about the CodeIgniter controller that has the function to upload the image file. We explain the code written above is first of all

  • Set the upload path.
  • Allow the types of files that you want to upload.
  • Set the size of an image file.
  • Set the name of image file.
  • Load the library of upload that is the Codeigniter library.
  • Upload the file.

These are simple steps that you need to follow and the image file name and other parameters insert into the database and the image file is saved in the folder that you set the path. You can further read about the database connection using CodeIgniter.
How to create connection with database in CodeIgniter...!

This Post Was Last Updated On September 30, 2016, By Author: Mahira Khan.

Tuesday, 9 February 2016

Form validation in codeigniter

Codeigniter form validation: The first thing is when we create the form for retrieving some data from the user then the user will enter the data in data fields that we created and so for we need to retrieve the correct data from our user. For that purpose, we use the form validation. Different types of form validation occur like using jquery form_validatiaon.js library, PHP form validation, CodeIgniter form validation. So we discuss the form validation using CodeIgniter form validation that is the simple and easy to use and accurate and most of the professionals use this type of validation.

Form validation in codeigniter

Three steps

1)In view where your form is designed in html call there a function
"<?php echo validation_errors(); ?>

2)If you are sending the form in new page address then there you should show a successful message

3)A controller receives the data then will validate it and if valid then submit to the database or anywhere you want.

Example
------------------------------------------------------------------
STEP 1)
addForm.php

<!-- codeigniter form validation -->
<?php echo validation_errors(); ?>
<form method="post" action="http://192.168.1.200/projects/NomanJ/dbcontroller/add" id="formSubmit" novalidate="novalidate">
    <div class="form-group">
      <label for="firstname">First Name</label>
      <input type="text" name="firstname" class="form-control" id="firstname" placeholder="firstname">
    </div>
    <div class="form-group">
      <label for="lastname">Last Name</label>
      <input type="text" name="lastname" class="form-control" id="lastname" placeholder="lastname">
    </div>
    <div class="form-group">
      <label for="email">Email</label>
      <input type="email" name="email" class="form-control" id="email" placeholder="example@gmail.com">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
------------------------------------------------------------------
STEP 2)
success.php
<html>
<head>
<title>My Form</title>
</head>
<body>
<h3>Your form was successfully submitted!</h3>
<p><?php echo anchor('form', 'Try it again!'); ?></p>
</body>
</html>
------------------------------------------------------------------
STEP 3)
<?php
class Form extends CI_Controller {
function index()
{
$this->load->library('form_validation');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('addForm');
}
else
{
$this->load->view('success');
}
}
}
?>
------------------------------------------------------------------

Form validation in codeigniter

It's one the most secure and accurate way to validate the data of web forms from the users other validation methods may have some drawbacks like HTML5  form validation only apply when you open the website in new web browsers and the jquery validation is also have some drawback that if the user disables the javascript from the browser then no validation will be on the website remains and he can start the SQL injection in the database of your website. You can read about the jquery form validation from here.
Jquery form validation ...!

This Post Was Last Updated On: September 28, 2016 By Author: Mahira Khan.