循环神秘地停在阵列中间

时间:2014-03-04 15:04:17

标签: php mysql

我对此感到疯狂。首先,我的代码是草率的&可怕,我知道,但它应该有用。

我正在使用SSH来执行脚本,所以据我所知,PHP中的时间限制自动设置为0,但无论我是否尝试将时间限制设置为0但不起作用。

如果它有帮助,我连接的数据库超过20密耳的记录&以前是内存错误。

脚本在第一个DMA的$ keys数组中停止'CPA'。 'tables'表永远不会将setup列更新为1,所以我知道循环正在停止。

没有错误,没有,只是在SSH中闪烁的光标。提前谢谢。

<?php
ini_set('memory_limit', '3072M');
ini_set('max_execution_time', 0);
define('RECORD_LIMIT', 100);

error_reporting(E_ALL);
ini_set('display_errors', '1');

$_SERVER['HTTP_HOST'] = 'listings.website.org';

require_once(dirname(__FILE__) . '\wp-config.php');
require_once(dirname(__FILE__) . '\wp-includes\post.php');
require_once(dirname(__FILE__) . '\wp-includes\wp-db.php');
require_once(dirname(__FILE__) . '\wp-includes\ms-load.php');
require_once(dirname(__FILE__) . '\wp-includes\ms-blogs.php');
require_once(dirname(__FILE__) . '\wp-includes\ms-functions.php');
require_once(dirname(__FILE__) . '\wp-admin\includes\taxonomy.php');

class WordPressImport
{
    private $db;
    private $wpCities, $wpStates = array();

    public function __construct()
    {
        try
        {
            $this->db = new PDO('mysql:host=localhost;dbname=l_business', 'user', '*****');
        }
        catch(PDOException $e)
        {
            Print ($e->getMessage());
            die();      
        }
        $this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    }

    public function process($query, $cities, $state, $blogid)
    {
        $counter = 1;
        $totalStmt = $this->db->prepare("SELECT COUNT(*) total 
                                           FROM business_data 
                                          WHERE business_name REGEXP :category AND
                                                business_city REGEXP :cities AND 
                                                business_state = :state");
        $totalStmt->execute(array('category' => $query, 
                                  'cities' => $cities, 
                                  'state' => $state));

        if ($totalStmt->rowCount() < 1) 
            throw new Exception('Quick check, but assuming we connect, will never happen.');

        $total = $totalStmt->fetchColumn();
        $resultStmt = $this->db->prepare("SELECT sic_id,
                                                 business_name,
                                                 business_address,
                                                 business_city,
                                                 business_state,
                                                 business_zip,
                                                 business_phone
                                            FROM business_data
                                           WHERE business_name REGEXP :category AND
                                                 business_city REGEXP :cities AND
                                                 business_state = :state
                                           LIMIT :rows OFFSET :offset");

        for ($i = 0; $i < $total; $i += RECORD_LIMIT)
        {
            echo 'Begin batch: '.($i + 1).'-'.($i + RECORD_LIMIT).' of '.$total.PHP_EOL;
            $resultStmt->bindValue(':category', $query, PDO::PARAM_STR);
            $resultStmt->bindValue(':cities', $cities, PDO::PARAM_STR);
            $resultStmt->bindValue(':state', $state, PDO::PARAM_STR);
            $resultStmt->bindValue(':offset', (int) $i, PDO::PARAM_INT);
            $resultStmt->bindValue(':rows', (int) RECORD_LIMIT, PDO::PARAM_INT);
            $resultStmt->execute();
            $last_state='';

            if ($resultStmt->rowCount() > 0)
            {
                while ($row = $resultStmt->fetch(PDO::FETCH_ASSOC))
                {
                    set_time_limit(0);
                    if($last_state=='')
                    {
                        $last_state=$row['business_state'];
                    }
                    else if(!($last_state==$row['business_state']))
                    {
                        //diffirent state now
                        unset($this->wpStates[$last_state]);
                        unset($this->wpCities[$last_state]);
                        $last_state=$row['business_state'];
                    }

                    $sicid = $row['sic_id'];
                    $bname = $row['business_name'];

                    if($query == 'breed')
                    {
                        $oldcat = 'animal & pet breeders';
                    }
                    elseif($query == 'advertising')
                    {
                        $oldcat = 'advertising consultants';
                    }
                    else
                    {
                        $oldcat = $query;
                    }

                    switch_to_blog($blogid, true);
                    wp_delete_post(1, true);
                    wp_delete_post(2, true);
                    $oldcat = ucwords($oldcat);

                    if(strpos($row['business_city'], ' Bch') === false)
                    {
                        $bcity = $row['business_city'];
                    }
                    else
                    {
                        $bcity = str_replace('Bch','Beach',$row['business_city']);
                    }

                    if(strpos($bcity, ' Shrs') !== false)
                    {
                        $bcity = str_replace('Shrs','Shores',$bcity);
                    }

                    $parentid = wp_create_category($oldcat);
                    $postcat = wp_create_category($oldcat.' in '.$bcity.', '.$row['business_state'], $parentid);
                    $postArr = array('comment_status' => 'closed',
                                     'ping_status'    => 'closed',
                                     'post_author'    => '1',
                                     'post_content'   => '',
                                     'post_date'      => date('Y-m-d H:i:s'),
                                     'post_excerpt'   => '',
                                     'post_name'      => sanitize_title(trim($bname.'-near-'.$bcity.'-'.$row['business_state'].'-'.$row['business_zip'].'-'.$row['business_phone'])),
                                     'post_status'    => 'publish',
                                     'post_title'     => $bname." In ".$bcity." ".$row['business_state']." ".$row['business_zip'],
                                     'post_type'      => 'post');

                    echo 'Insert Post: '.$counter.' '.$bname.' In '.$bcity.', '.$row['business_state'].' '.$row['business_zip'].' Phone:'.$phone.' - cat:'.$oldcat.'<br>'.PHP_EOL;
                    $phone = preg_replace('/(\d{3})(\d{3})(\d{4})/', '($1) $2-$3',     $row['business_phone']);
                    $postID = wp_insert_post($postArr);
                    wp_set_post_categories($postID, $postcat);

                    //wp_set_post_tags($postID, $catname);
                    add_post_meta($postID, 'mu_name', $bname, true);
                    add_post_meta($postID, 'mu_address', $row['business_address'], true);
                    add_post_meta($postID, 'mu_phone', $phone, true);
                    add_post_meta($postID, 'mu_city', $bcity, true);
                    add_post_meta($postID, 'mu_state', $row['business_state'], true);
                    add_post_meta($postID, 'mu_zip', $row['business_zip'], true);
                    add_post_meta($postID, 'mu_cat', $oldcat, true); 
                    $counter++;
                }
            }

            //show memory usage
            echo ('current memory usage '.memory_get_usage().PHP_EOL);
        }
    }
}

try
{
    if (PHP_SAPI == 'cli')
    {
        if (!is_multisite()) 
            throw new Exception('Something isn\'t right. Is this multi-site?');

        $keys = array('equipment rentals','equipment repair','florist','boarding',' pet care','grooming','stables','dog training','Veterinarian','advertising','business consult','commercial clean','computer store','computer repair','website design',' cement ',' deck ','domolition','drywall','electrician',' fence','carpent','floor','general contract','excavation','handyman','a/c ','cabinet','labor ','painting','plumbing','roof','siding',' tile','window repair','art school','drivers ed','flight school','music school','tutor','entertainment','wedding','catering','nutritionist','chef','Acupuncture','chiropractor','counselor','dentist','funeral','hospice','nails','massage','nursing','personal train','babysit','carpet clean','day care','maid','interior decor','drain','housekeeper','pest control','pool care','septic','window clean','landscape maintenance','landscape design','irrigation','brush clearing','tree service','lawn care','bankruptcy law','civil law','court report','criminal law','estate law','family law','notary','injury law','process server','real estate law','tax law','trademark law','fabricat','machine shop','millwork','storage','junk remov','moving','cpa','bookkeep','photograph','publish','investigat',' sign ','tax preperation','real estate apprais','real estate brok','real estate inspection','property maintenance','property manage','title compan','archery','dance','gymnastic','martial arts','skating','yoga','antique','appliance repair','clock','furniture repair',' gun','music repair','office repair','camera repair','equipment repair','tool repair','alarm system','garage door','gutter','locksmith','screen repair','weld','home theater','phone system','airplane charter','limousine','boat charter','taxi ','Bed & Breakfast','hotel','resort','travel agent','vacation home','auto paint','custom auto','auto detail','machine shop','auto repair','car rent','auto storage','towing','boat rental','boat repair','boat slip','boat storage','boat transport','web design','concrete','patio','therapist','lawn mow','patent law','mover','accountant','banner','karate','security system','jet charter','chauffer','boat tour','shuttle','motel',' spa ','vacation rent','car wash','auto rent','auto transport','business card');

        $db2 = mysql_connect('localhost', 'user', '********', TRUE);
        mysql_select_db('fl_orlando', $db2);

        $sql = "SELECT * FROM tables WHERE setup = '0'"; $re = mysql_query($sql, $db2);

        while($row = mysql_fetch_object($re))
        {
            $cities = array();
            $sql6 = "SELECT * FROM dma_cities WHERE dma = '$row->dma'"; 
            $re6 = mysql_query($sql6, $db2);
            while($row6 = mysql_fetch_object($re6))
            {
                $cities[] = $row6->name;
            }

            $cit = implode('|', $cities); 
            $dma = $row->dma;
            $path = strtolower($dma);
            $path = str_replace(' ', '-', $path);
            $path = str_replace(')', '', $path);
            $path = str_replace('(', '', $path);
            $path = str_replace(',', '', $path);
            $path = str_replace('.', '', $path);
            $path = '/'.$path.'/';
            $states = array();
            $states[] = $row->state_1;
            if(!empty($row->state_2))
            { 
                $states[] = $row->state_2; 
            }

            if(!empty($row->state_3))
            { 
                $states[] = $row->state_3; 
            }

            $newblog = wpmu_create_blog('listings.website.org', $path, $dma.' Area', '1');

            $sql7 = "UPDATE tables SET listing_id = '$newblog', listing_url = 'listings.website.org$path' WHERE dma = '$dma'"; 
            mysql_query($sql7, $db2);
            foreach($states as $state)
            {
                foreach($keys as $cats)
                {
                    set_time_limit(0);
                    $import = new WordPressImport();
                    $import->process($cats, $cit, $state, $newblog); 
                }
            }

            $sql8 = "UPDATE tables SET setup = '1' WHERE dma = '$dma'";
            mysql_query($sql8, $db2); 
        }
    }
    else
    {
        throw new Exception('Wrong environment, DO NOT run from a web server.');
    }
}
catch (Exception $e)
{
    echo 'Exception: '.$e->getMessage().PHP_EOL;
}

0 个答案:

没有答案