简体   繁体   中英

How to add two columns from two tables in MySQL?

I have 3 tables: controller, allot_compnts and prev_allot_compnts, 3 tables have same fields, when i click on submit button, values in allot_compnts is copied to prev_allot_compnts and deletes from allot_compnts

Code :

  $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]'";

      }

I'm trying to update num_comp in controller table based on $_POST[num_comp],but the value in controller table not updating

I'm new to this, please any one help me how to do this

Update: i just updated my code to

$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'";

      }

Sill not working

Your $sql variable with $_POST['num_comp'] = 123 is parsed as UPDATE comp_controller SET num_comp=(num_comp+123) WHERE comp_name ='Some name' ON DUPLICATE KEY UPDATE num_comp=num_comp+'123'

Possible errors

  1. isset($_POST['num_comp'])? $_POST['num_comp'] :'';

You empty the value num_comp, if num_comp is not sent in the POST request. This will automatically lead to SET num_comp=(num_comp+) which is no longer a valid SQL statement.

  1. num_comp=num_comp+'$_POST[num_comp]'

Is parsed as num_comp=num_comp+'123' . You try to add a string to a number.

  1. ON DUPLICATE KEY UPDATE

As far as I know ON DUPLICATE KEY UPDATE is only valid with the INSERT statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM