Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • PHP Script to import any excel database in MySql

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 696
    Comment on it

    Hello Friends,

    If you want to import any excel sheet to your My SQL database you can use the following code below. I have specified comments wherever needed.This is complete script and here you need to keep the classes directory with your code.

    <?php
    //Database connection
        $con = mysqli_connect("Host_Name", "User_Name", "Password", "Database_Name");
    // Check connection
    if (mysqli_connect_errno($con)) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    
      //Getting existing records
        $result = mysqli_query($con, "SELECT running_for,district,political_party,bio_headline,candidate_twitter_feed,candidate_twitter_follow,candidate_facebook_like,candidate_link_phone,candidate_link_bio,endorsements,candidate_news_link,candidate_link_yardsign,candidate_link_stickers,candidate_link_newsletter,candidate_video_page,candidate_calender,candidate_issue_page,candidate_defense_issue,candidate_economy_issue,candidate_health_issue,candidate_tax_issue,candidate_jobs_issue,candidate_nsa_surveillance_reform_issue,candidate_energy_issue,candidate_education_issue,candidate_security_entitlement_issue,candidate_immigration_issue,volunteer_us,paypal_donation_link,link_register_votepage,candidate_polling_place,candidate_free_ride,created,modified FROM candidates");
        $exist_records = array();
        while ($row = mysqli_fetch_array($result)) {
            $exist_records[$row[0]] = $row;
        }
    
    // Include Classes
    include 'classes/PHPExcel/IOFactory.php';
    //Inventory data
    $invFileName = 'Congresional2.xlsx';               // File to read
    echo 'Loading file ', pathinfo($inputFileName, PATHINFO_;BASENAME), ' using IOFactory to identify the format<br /-->';
    
    try {
        $objPHPExcel = PHPExcel_IOFactory::load($invFileName);
    } catch (Exception $e) {
        die('Error loading file "' . pathinfo($invFileName, PATHINFO_BASENAME) . '": ' . $e-&gt;getMessage());
    }
    
    $invData = $objPHPExcel-&gt;getActiveSheet()-&gt;toArray(null, true, true, true);
    array_shift($invData);
    foreach ($invData as $data) {
        set_time_limit(1000);
        $item_id = str_replace('"', '', $data['A']);
        //Get invetory data for item
        if (in_array($item_id, $items)) {
            //Creating a common array
            $inv_records[$item_id] = $data['C'];
        }
    }
    // user data
    $inputFileName = 'Congresional2.xlsx';  // File to read
    echo 'Loading file ', pathinfo($inputFileName, PATHINFO_BASENAME), ' using IOFactory to identify the format<br>';
    try {
        $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
    } catch (Exception $e) {
        die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e-&gt;getMessage());
    }
    $sheetData = $objPHPExcel-&gt;getActiveSheet()-&gt;toArray(null, true, true, true);
    array_shift($sheetData);
    
    $count = sizeof($sheetData);
    
    //the top line is the field names the field names which are to be used for insertion
    $fields = array('S.no', 'State', 'abbr','district', 'Party', 'Candidate_Name', 'Email', 'FB_Account', 'Twitter_Account', 'Candidate_Website_Home_Page', 'Bio', 'Endorsements', 'News', 'Videos', 'Calendar_Events', 'Issues', 'Issues1', 'Issues2', 'Issues3', 'Issues4', 'Issues5', 'Issues6', 'Issues7', 'Issues8', 'Issues9', 'Issues10', 'Volunteer', 'Sign-Up_Newsletter', 'Yard_Sign', 'Bumper_Sticker', 'Telephone', 'Donate');
    $records = array();
    $i = 0;
    foreach ($sheetData as $data) {
        set_time_limit(10000);
    // Fields to be unset which are not required from excel sheet
        unset($data['G'], $data['K'], $data['L'], $data['M'], $data['AK'], $data['AL'], $data['AM'], $data['AN']);
     // combining both the array  
     $temp = array_combine($fields, $data);
        //Get invetory data for item
        $records[$i] = $temp;
        $i++;
        if (in_array($count, $temp)) {
         //Creating a common array
          $records[$candidate] = $temp;
            break;
        }
    }
    //Complete field array
    // Field Array consisting field names of database table
    
    //As I am inserting values in two tables therefore i am using two variables($fields, $field_str).
    // User Table
    $fields = 'username,email,password,created,modified,status,type';
    
    //candidate table
    $field_str = 'district,running_for,user_id,state,political_party,bio_headline,candidate_twitter_feed,candidate_twitter_follow,candidate_facebook_like,candidate_link_phone,candidate_link_bio,endorsements,candidate_news_link,candidate_link_yardsign,candidate_link_stickers,candidate_link_newsletter,candidate_video_page,candidate_calender,candidate_issue_page,candidate_defense_issue,candidate_economy_issue,candidate_health_issue,candidate_tax_issue,candidate_jobs_issue,candidate_nsa_surveillance_reform_issue,candidate_energy_issue,candidate_education_issue,candidate_security_entitlement_issue,candidate_immigration_issue,volunteer_us,paypal_donation_link,link_register_votepage,candidate_polling_place,candidate_free_ride,created,modified';
    
    $i = 0;
    $image_path = '';
    foreach ($records as $record) {
    // If no record found it should exit from loop   
     if($record['S.no'] == "" ){
         break;
       }
        $sqlusers = "INSERT INTO users (" . $fields . ")
                VALUES
                ('" . $record['Candidate_Name'] . "', '" . $record['Email'] . "', 'b9014def59a576fcfa7a79c337ab16ee13add66d','2014-04-28 15:32:28','2014-04-28 15:56:31','Active','user' )";
    // Getting the last inserted record ID from Users Table to insert it into Candidate table
        mysqli_query($con, $sqlusers);
        $candidateid = mysqli_insert_id($con);
        $sql = "INSERT INTO candidates (" . $field_str . ")
                VALUES
                ('" . $record['district'] . "','Congressman','" . $candidateid . "', '" . $record['abbr'] . "', '" . $record['Party'] . "', '" . $record['Candidate_Website_Home_Page'] . "', '" . $record['Twitter_Account'] . "', '" . $record['Twitter_Account'] . "', '" . $record['FB_Account'] . "', '" . $record['Telephone'] . "', '" . $record['Bio'] . "', '" . $record['Endorsements'] . "', '" . $record['News'] . "', '" . $record['Yard_Sign'] . "', '" . $record['Bumper_Sticker'] . "', '" . $record['News'] . "', '" . $record['Videos'] . "','" . $record['Calendar_Events'] . "','" . $record['Issues'] . "','" . $record['Issues1'] . "','" . $record['Issues2'] . "','" . $record['Issues3'] . "','" . $record['Issues4'] . "','" . $record['Issues5'] . "','" . $record['Issues6'] . "','" . $record['Issues7'] . "','" . $record['Issues8'] . "','" . $record['Issues9'] . "','" . $record['Issues10'] . "','" . $record['Volunteer'] . "','" . $record['Donate'] . "','http://votetexas.gov/register-to-vote/','http://www.votetexas.gov/voting/where','http://www.ridetovote.org/','2014-05-01 10:56:31','2014-05-01 10:56:31')";
        if (mysqli_query($con, $sql)) {
           $i++;
       }
       if($record['S.no'] == "" ){
        break;
       }
    }
    echo $i . " records updated";
    // close the connection for image ftp
    ?&gt;
    
    <!--?php
    /**
     * function for format string withoung " around string and add escapes
     * */
    function otrim($string) {
        if ($string != '') {
            if ($string[0] == '"')
                $string = substr($string, 1);
            if ($string[strlen($string) - 1] == '"')
                $string = substr($string, 0, strlen($string) - 1);
        }
        return mysql_real_escape_string($string);
    }
    ?-->
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: