如何从MySQL中的两个表中添加两列?

时间:2016-12-27 07:28:02

标签: php mysql database

我有3个表:controller,allot_compnts和prev_allot_compnts,3个表有相同的字段,当我点击提交按钮时,allot_compnts中的值被复制到prev_allot_compnts并从allot_compnts删除

代码:

  $id=@$_POST['submit']
  $type = isset($_POST['comp_type'])? $_POST['comp_type'] : '';
  $name = isset($_POST['comp_name'])? $_POST['comp_name'] :'';
  $comp = isset($_POST['num_comp'])? $_POST['num_comp'] :'';

 //Insert

 $sql1="INSERT INTO prev_alloted_comp(id,comp_type,comp_name,num_comp)
 SELECT comp_type,comp_name,num_comp FROM alloted_comp WHERE id='$id'" ;

 //Delete

 $sql2="delete from alloted_comp where id='$id'";

 //Here i'm trying to update controller table 

  if($type === 'Controller'){  

      $sql3= "UPDATE comp_controller SET 
      num_comp=(num_comp+$_POST[num_comp]) WHERE comp_name ='$name'
      ON DUPLICATE KEY UPDATE num_comp=num_comp+'$_POST[num_comp]'";

      }

我尝试根据$ _POST [num_comp]更新控制器表中的num_comp,但控制器表中的值未更新

我是新手,请任何人帮助我如何做到这一点

更新:我刚刚将代码更新为

$id=@$_POST['submit']
  $type = isset($_POST['comp_type']);
  $name = isset($_POST['comp_name']);
  $comp = isset($_POST['num_comp']);

 //Insert

 $sql1="INSERT INTO prev_alloted_comp(id,comp_type,comp_name,num_comp)
 SELECT comp_type,comp_name,num_comp FROM alloted_comp WHERE id='$id'" ;

 //Delete

 $sql2="delete from alloted_comp where id='$id'";

 //Here i'm trying to update controller table 

  if($type === 'Controller'){  

      $sql3= "UPDATE comp_controller SET 
      num_comp=(num_comp+$_POST[num_comp]) WHERE comp_name ='$name'";

      }

不能正常工作

1 个答案:

答案 0 :(得分:0)

$sql $_POST['num_comp'] = 123变量UPDATE comp_controller SET num_comp=(num_comp+123) WHERE comp_name ='Some name' ON DUPLICATE KEY UPDATE num_comp=num_comp+'123'被解析为isset($_POST['num_comp'])? $_POST['num_comp'] :'';

可能的错误

  1. SET num_comp=(num_comp+)
  2. 如果POST请求中未发送num_comp,则清空值num_comp。这将自动导致num_comp=num_comp+'$_POST[num_comp]'不再是有效的SQL语句。

    1. num_comp=num_comp+'123'
    2. 被解析为ON DUPLICATE KEY UPDATE。您尝试将字符串添加到数字。

      1. ON DUPLICATE KEY UPDATE
      2. 据我所知,$date = '2016-12-01'; //Your script start date, you wont need to change this anymore $everyxdate = 10; // once x days to add x to $date $days_passed = date_create()->diff(date_create($date))->days; // passed days from start of script $date $mod_dates = (int)($days_passed / $everyxdate); // count how much cycles have passed $daystoadd = $mod_dates * $everyxdate + $everyxdate; // count how much days we need to add $newdate = strtotime ("+$daystoadd day" , strtotime ( $date ) ) ; // Add needed day count to starting $date $newdate = date ( 'd.m.y' , $newdate ); // Format date the way you want 仅适用于INSERT声明。