dpymrcl269187540 2014-04-01 01:36
浏览 56
已采纳

检索MySQL表时克服PHP内存耗尽或执行时错误

I have a big table in my MySQL database. I want to go over one of it's column and pass it in a function to see if it exist in another table and if not create it there.

However, I always face either a memory exhausted or execution time error.

//Get my table
$records = DB::($table)->get();

//Check to see if it's fit my condition
foreach($records as $record){
    Check_for_criteria($record['columnB']);
}

However, when I do that, I get a memory exhausted error.

So I tried with a for statement

//Get min and max id
$min = \DB::table($table)->min('id');
$max = \DB::table($table)->max('id');

//for loop to avoid memory problem
for($i = $min; $i<=$max; $i++){
    $record = \DB::table($table)->where('id',$i)->first();

    //To convert in array for the purpose of the check_for_criteria function
    $record= get_object_vars($record);
    Check_for_criteria($record['columnB']);   
}

But going this way, I got a maximum execution time error.

FYI the check_for_criteria function is something like

check_for_criteria($record){
    $user = User::where('record', $record)->first();
    if(is_null($user)){
        $nuser = new User;
        $nuser->number = $record;
        $nuser->save();
    }
}

I know I could ini_set('memory_limit', -1); but I would rather find a way to limit my memory usage in some way or at least spreading it some way.

Should I run these operations in background when traffic is low? Any other suggestion?

  • 写回答

1条回答 默认 最新

  • dongzhuo1880 2014-04-01 02:10
    关注

    I solved my problem by limiting my request to distinct values in ColumnB.

    //Get my table
    $records = DB::($table)->distinct()->select('ColumnB')->get();
    
    //Check to see if it's fit my condition
    foreach($records as $record){
        Check_for_criteria($record['columnB']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式