0

*$conn->query($insert_statement.$values);* にコメントしない限り、一定のループにとどまる次のコードがあります。その行にコメントを付けると、最後の挿入ステートメントでループが終了するため、正確に正しい印刷出力が得られます。

for($count =0; $count < $rs->num_rows; $count++){
        $values = "";
        foreach($keys as $key){        
            $values = $values . "'".$row->$key."', ";
        }        
        $values = substr($values, 0, strlen($values)-2) . ");\n";
        echo $insert_statement.$values."\n";
        $conn->query($insert_statement.$values);
}

これがコード全体です。テーブルをバックアップするスクリプトを作成しようとしています。

<?

$date = getdate();

$date = $date['month']."_".$date['mday']."_".$date['year'];



$conn = new mysqli("localhost", "root", "ranger", "customers");

$conn->query("drop table if exists backup_$date");
$rs = $conn->query("DESCRIBE customers");

$create_statment = "create table backup_$date (";

$primary_key = "";
$keys = array();
$insert_statement = "insert into backup_$date (";

$count = 0;
while($row = $rs->fetch_object()) {
    if($count > 0){
        $keys[] =  "".$row->Field."";
        $insert_statement = $insert_statement . "`".$row->Field."` ,";
    }
    if($row->Null == "NO"){
        $create_statment = $create_statment . "`".$row->Field."` ".$row->Type." not null";        
        if($row->Extra == "auto_increment"){
            $create_statment = $create_statment ." not null auto_increment, ";      
        }else{
            $create_statment = $create_statment . ",";
        }
    }else{
        $create_statment = $create_statment . " `".$row->Field."` ".$row->Type.", ";
    }
    if($row->Key == 'PRI'){
        $primary_key = "primary key(".$row->Field.")";        
    }
    $count++;
}
$create_statment = $create_statment . " $primary_key);";

$conn->query($create_statment);





$rs = $conn->query("select * from customers;");

$insert_statement = substr($insert_statement, 0, strlen($insert_statement)-1).") values (";
$row = $rs->fetch_object();
for($count =0; $count < $rs->num_rows; $count++){
        $values = "";
        foreach($keys as $key){        
            $values = $values . "'".$row->$key."', ";
        }        
        $values = substr($values, 0, strlen($values)-2) . ");\n";
        echo $insert_statement.$values."\n";
        $conn->query($insert_statement.$values);
}



?>
4

1 に答える 1

1

INSERT ... SELECTを使用してバックアップを作成します。多分これはあなたを助けます。

于 2013-01-07T01:22:01.193 に答える