简体   繁体   English

如何使用具有动态值的变量更新sql表

[英]How to update sql table by using a variable which has dynamic value

I have a php code which sums up the value of the same column from two different tables of same database and stores it in a variable. 我有一个PHP代码,它从同一个数据库的两个不同表中汇总同一列的值,并将其存储在一个变量中。 The code is mentioned below: 代码如下:

$sql = 'SELECT
        (SELECT SUM( time_spent )
         FROM '.TICKET_RESPONSE_TABLE.'
         WHERE ticket_id='.db_input($id).')
        +(SELECT SUM( time_spent )
          FROM '.TICKET_NOTE_TABLE.'
          WHERE ticket_id='.db_input($id).')
    AS total_time';
$result = db_query($sql);
$cursor = mysql_fetch_row($result);
$total_time = $cursor[0];

Now,I want is to update a column in another table of the same database, with the value stored in the variable $total_time. 现在,我想要更新同一数据库的另一个表中的列,其值存储在变量$ total_time中。 Kindly help me with the same. 请帮助我。

You can do a direct update instead of having on a variable. 您可以直接更新,而不是使用变量。

$sql = 'UPDATE *tablename*
        SET *columname* = 
        (SELECT SUM( time_spent )
         FROM '.TICKET_RESPONSE_TABLE.'
         WHERE ticket_id='.db_input($id).')
        +(SELECT SUM( time_spent )
          FROM '.TICKET_NOTE_TABLE.'
          WHERE ticket_id='.db_input($id).')';
$result = db_query($sql);

or afterwords like this: 或像这样的后记:

$sql = 'SELECT
        (SELECT SUM( time_spent )
         FROM '.TICKET_RESPONSE_TABLE.'
         WHERE ticket_id='.db_input($id).')
        +(SELECT SUM( time_spent )
          FROM '.TICKET_NOTE_TABLE.'
          WHERE ticket_id='.db_input($id).')
    AS total_time';
$result = db_query($sql);
$cursor = mysql_fetch_row($result);
$total_time = $cursor[0];
$sql = 'SUPDATE *tablename*
            SET *columname* = ' . $total_time
$result = db_query($sql);

You can make a subselect: 您可以进行子选择:

UPDATE table1 t1
SET t1.val1 =
(SELECT val FROM table2 t2 WHERE t2.id = t1.t2_id )
WHERE t1.val1 = '';

Why not $sql= "INSERT INTO other table SET field_name = $total_time "; 为什么不$ sql =“INSERT INTO其他表SET field_name = $ total_time”; $result = db_query($sql); $ result = db_query($ sql);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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