草庐IT

php - 在 mysql 表中找到 "problematic"行将无法导出

coder 2023-10-16 原文

我想 backup my database with PHP .

我测试了链接脚本,但它永远不会结束,我试图在查询之前添加 repair $table 但它没有帮助。

所以我想如果我只是跳过两个表(你可以在代码中看到)那么它工作正常:

<?

error_reporting(E_ALL);
ini_set('error_reporting',1);
require('../basedatos.php');

echo 'included<br>';
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{


    echo '1<br>';
    //get all of the tables
    if($tables == '*')
    {
        $tables = array();
        $result = mysql_query('SHOW TABLES') or die(msyql_error());
        while($row = mysql_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }
    echo '2<br>';
    //cycle through
    foreach($tables as $table)
    {
        if($table == 'etiquetas' || $table == 'links') continue;
        $repair = mysql_query("REPAIR table $table") or die(mysql_error());
        echo '3- '.$table.'<br>';
        $result = mysql_query('SELECT * FROM '.$table) or die(msyql_error());
        $num_fields = mysql_num_fields($result);

        $return.= 'DROP TABLE '.$table.';';
        $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table))  or die(msyql_error());
        $return.= "\n\n".$row2[1].";\n\n";

        for ($i = 0; $i < $num_fields; $i++) 
        {
            while($row = mysql_fetch_row($result))
            {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j<$num_fields; $j++) 
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = ereg_replace("\n","\\n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";

    }
    echo '4<br>';
    //save file
    $handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
    fwrite($handle,$return);
    fclose($handle);
}
backup_tables('localhost','username','password','*');
?>

有什么方法可以找到给我带来问题的行,以便我可以编辑/删除它们?

-附言-

此外,如果我不跳过它们,我不会收到任何错误(脚本永远不会结束,这就是为什么我添加了一些丑陋的日志..,知道为什么吗?

-编辑-

此外,如果我尝试通过例如 sqlBuddy 导出数据库,我也会遇到错误:

最佳答案

正如许多人所说,这个脚本(以及简单的“通过 PHP 进行 MySQL 转储”)远非最佳,但总比没有备份好。

由于您只能使用 PHP 访问数据库,因此您应该使用它来找出问题所在。

这是对您的脚本的改编,它只会将一个表转储到一个文件中。它是一个调试脚本,而不是用于生产的导出工具(但是,用它做你想做的事),这就是为什么它在保存表的每一行后输出调试。

正如 Amit Kriplani 所建议的那样,每次迭代都会将数据附加到目标文件,但我认为 PHP 内存不是您的问题,如果内存不足或至少是 HTTP 500,您应该会收到 PHP 错误应该由服务器抛出而不是永远运行脚本。

function progress_export( $file, $table, $idField, $offset = 0, $limit = 0 )
{

    debug("Starting export of table $table to file $file");

    // empty the output file
    file_put_contents( $file, '' );
    $return = '';

    
    debug("Dumping schema");

    $return.= 'DROP TABLE '.$table.';';
    $row2 = mysql_fetch_row(mysql_query("SHOW CREATE TABLE $table"));
    $return.= "\n\n".$row2[1].";\n\n";

    
    file_put_contents( $file, $return, FILE_APPEND );

    debug("Schema saved to $file");




    $return = '';

    debug( "Querying database for records" );

    $query = "SELECT * FROM $table ORDER BY $idField";

    // make offset/limit optional if we need them for further debug
    if ( $offset && $limit )
    {
        $query .= " LIMIT $offset, $limit";
    }

    $result = mysql_query($query);
    
    $i = 0;
    while( $data = mysql_fetch_assoc( $result ) )
    {
        // Let's be verbose but at least, we will see when something goes wrong
        debug( "Exporting row #".$data[$idField].", rows offset is $i...");

        $return = "INSERT INTO $table (`". implode('`, `', array_keys( $data ) )."`) VALUES (";
        $coma = '';

        foreach( $data as $column )
        {
            $return .= $coma. "'". mysql_real_escape_string( $column )."'";
            $coma = ', ';
        }

        $return .=");\n";

        file_put_contents( $file, $return, FILE_APPEND );

        debug( "Row #".$data[$idField]." saved");

        $i++;
        
        // Be sure to send data to browser
        @ob_flush();
    }

    debug( "Completed export of $table to file $file" );
}



function debug( $message )
{
    echo '['.date( "H:i:s" )."] $message <br/>";
}


// Update those settings :

$host = 'localhost';
$user = 'user';
$pass = 'pwd';
$base = 'database';

// Primary key to be sure how record are sorted
$idField = "id"; 

$table   = "etiquetas";

// add some writable directory
$file = "$table.sql";


$link = mysql_connect($host,$user,$pass);
mysql_select_db($base,$link); 




// Launching the script
progress_export( $file, $table, $idField );

编辑脚本末尾的设置并针对您的两个表之一运行它。

您应该在脚本仍在处理时看到输出,并获得有关正在处理的行的一些引用,如下所示:

[23:30:13] Starting export of table ezcontentobject to file ezcontentobject.sql

[23:30:13] Dumping schema

[23:30:13] Schema saved to ezcontentobject.sql

[23:30:13] Querying database for records

[23:30:13] Exporting row #4, rows offset is 0...

[23:30:13] Row #4 saved

[23:30:13] Exporting row #10, rows offset is 1...

[23:30:13] Row #10 saved

[23:30:13] Exporting row #11, rows offset is 2...

[23:30:13] Row #11 saved

[23:30:13] Exporting row #12, rows offset is 3...

[23:30:13] Row #12 saved

[23:30:13] Exporting row #13, rows offset is 4...

[23:30:13] Row #13 saved

etc.

如果脚本完成...

好吧,你会有一个表的备份(注意,我没有测试生成的 SQL)!

我猜它不会完成:

如果脚本没有到达第一个“Exporting row...”调试语句

那么问题出在查询的时候。

然后你应该尝试用偏移量和限制参数来限制查询,继续二分法找出它卡在哪里

生成查询的示例仅限于前 1000 个结果。

// Launching the script
progress_export( $file, $table, $idField, 0, 1000 );

如果脚本显示一些行在挂起之前被导出

在确定显示的最后一行 id 之前,您应该尝试:

  1. 再次运行脚本,看它是否卡在同一行。这是为了查看我们是否面临“随机”问题(它从来都不是真正随机的)。

  2. 为函数调用添加一个偏移量(参见可选参数),然后第三次运行脚本,看它是否仍然卡在同一行。

例如 50 作为偏移量,一些大数字作为限制:

// Launching the script
progress_export( $file, $table, $idField, 50, 600000 );

这是为了检查它自己的行是否导致了问题,或者它是否是临界行数/数据量...

  • 如果每次都返回相同的最后一行,请检查并反馈给我们。

  • 如果添加偏移量以可预测的方式更改最后处理的行,我们可能会在某处遇到资源问题。

如果您不能在分配的资源上玩游戏,那么解决方案就是将导出拆分成多个 block 。 您可以使用接近于此的脚本来完成此操作,输出一些 HTML/javascript,以自身重定向,以偏移量和限制作为参数,而导出未完成(如果这是我们最终需要的,我将编辑答案)

  • 如果行几乎每次都改变,它会变得更复杂......

一些线索:

我没有任何使用 VPS 的经验,但是你们对 CPU 使用没有一些限制吗?

如果您一次使用过多的资源,您的进程是否会以某种方式排队?

那些没有问题的转储表呢?是否有与导致问题的两个表一样大的表?

关于php - 在 mysql 表中找到 "problematic"行将无法导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18000676/

有关php - 在 mysql 表中找到 "problematic"行将无法导出的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  4. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  5. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  6. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  7. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  8. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  9. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

  10. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

随机推荐