bandito40
bandito40

Reputation: 637

php mysql infinite loop

I have the following code which stays in a constant loop unless I comment *$conn->query($insert_statement.$values);*. With that line commented I get exactly the correct printed output as it will finish the loop at the last insert statement.

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);
}

Here's the entire code. I am trying to make a script the backs up a table.

<?

$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);
}



?>

Upvotes: 0

Views: 553

Answers (1)

declonter
declonter

Reputation: 321

I create backup using INSERT ... SELECT. Maybe this helps you.

Upvotes: 1

Related Questions