在数据库表中将php一行移动到另一行

时间:2012-06-19 17:55:39

标签: php mysql

我正在使用php在我的数据库上制作一些mods,我有两个相同的表,我想从第一个表移动到第二个表,我怎么能用纯php和mysql做到这一点。

这就是我的表格的样子

CREATE TABLE users (
 username varchar(30) primary key,
 password varchar(32),
 userid varchar(32),
 userlevel tinyint(1) unsigned not null,
 email varchar(50),
 timestamp int(11) unsigned not null
);

这是我到目前为止的PHP代码

function procMoveUser(){
          global $session, $database, $form;
          /* Username error checking */
          $subuser = $this->checkUsername("user");

          /* Errors exist, have user correct them */
          if($form->num_errors > 0){
             $_SESSION['value_array'] = $_POST;
             $_SESSION['error_array'] = $form->getErrorArray();
             header("Location: ".$session->referrer);
          }
          /* move the user */
         else{

      $q = "SELECT * FROM ".TBL_USERS." WHERE username = '$subuser'"; 
      $result = $database->query($q); 

      if($result && $result->num_rows == 1){
          while($array = $result->fetch_assoc() ){
              $second_query = "INSERT INTO".TBL_USERSDONT."VALUES ($array['user'], $array['password'], $array['userid'] , $array['userlevel'] , $array['email'] , $array['timestamp'])"; 
              $second_result = $mysqli->query($second_query);
              if($second_result){
                  // it worked!
                  $q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";
                  $database->query($q);
              }
        }
      }




  }
       }

2 个答案:

答案 0 :(得分:1)

首先,SELECT * FROM要移动的行的第一个表。然后,如上所述,使用第一个表中的值运行INSERT语句。

$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'"; 
$result = $mysqli->query($q); 

if($result && $result->num_rows == 1){
    while($array = $result->fetch_assoc() ){
        $second_query = "INSERT INTO second_table VALUES ($array['user'], $array['something'])"; 
        $second_result = $mysqli->query($second_query);
        if($second_result){
        // it worked!
        }
    }
 }

答案 1 :(得分:0)

也许这会有所帮助:Copy an existing MySQL table to a new table