duandao1931 2016-01-29 11:10
浏览 119

使用PHP中的MySQL获取函数计算表中2个字段的总和

I have a table having the following fields: id(Autoincrement/Primary Key)/Integer1/Integer2/Sum/Product). I have filled integer1 and integer2 with the following code:

    for ($i=1;$i<=1000;$i++)
{
    $x2=rand(0,100);
    $x3=rand(0,100);
    $sql="INSERT INTO data(integer1,integer2) VALUES ($x2,$x3)";
$conn->query($sql);     
}

My PHPMyAdmin is now this, with the sum and product at default values, 0.

I need help to prepare a function which uses MySQLFetch and computes sum of integer1 and integer2 and assigns the value in sum and product. I know it can be done using a simple loop, but would really like to get an understanding of fetching data.

  • 写回答

3条回答 默认 最新

  • dssk35460 2016-01-29 11:16
    关注

    Assuming you are using mysqli which is how it appears with the use of $conn->query() then this might be of interest.

    /* establish db connection */
    $dbhost =   'localhost';
    $dbuser =   'root'; 
    $dbpwd  =   'xxx'; 
    $dbname =   'xxx';
    $conn   =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
    
    /* select records to to perform sum & product upon */
    $sql='select * from `data`';
    $res=$conn->query( $sql );
    if( $res ){
    
        /* prepare a new sql statement to update db records */
        $sql='update `data` set `sum`=?, `product`=? where `id`=?;';
        $stmt=$conn->prepare( $sql );
    
        while( $rs=$res->fetch_object() ){
            /* make some variables with records for each record */
            $id=$rs->id;
            $int_1=$rs->integer1;
            $int_2=$rs->integer2;
    
            /* basic maths operations */
            $sum=$int_1+$int_2;
            $product=$int_1 * $int_2;
    
            /* bind the variables into declared statement & execute */
            $stmt->bind_param( 'iii', $sum, $product, $id );
            $stmt->execute();
        }
        /* tidy up */
        $stmt->close();
        $conn->close();
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题