douhui3760 2017-01-20 08:53
浏览 11
已采纳

如何从文本框值增加mysql值?

Im trying to update a value in MySQL, to increase a number.Lets say that current value is 50, and if I will type 50 in the text-box, mysql value to become 100. Actually with the code below its only updating with the current text-box value.

     function updateMaterial($code){
                global $conn;
                $sql = $conn->prepare("SELECT * FROM stock WHERE itemcode = '$code'");
                $sql->execute();
                while($row = $sql->fetch(PDO::FETCH_ASSOC)){
                    $this->id = $row['id'];
                }
                if(isset($_POST['qty'])){

                     $sql = $conn->prepare("UPDATE stock SET qty='qty +$this->qty' WHERE id='$this->id'");
                     $sql->execute();

                }

            }

if(isset($_POST['update'])){
    $code = $_POST['itemcode'];
    if($addstock->updateMaterial($code)){
     return true;
    }else{
     return false;
    }
}
  • 写回答

1条回答 默认 最新

  • duankuai6586 2017-01-20 08:57
    关注

    You have the column name inside the quote, I would say that the query is in fact failing as you have it, but you are not checking for errors. To prove this supposition, test by passing 10 from the screen and see that the value of 50 in the database never changes.

    You should also be using prepared statement, to protect against SQL Injection

    Also you first query serves no purpose, if you can get the row using the code as the key then use it in the Update query.

    Also as this appears to be a method of a class the $conn variable should not be collected using global it destroys the encapsulation of the class. It should be a class property

    class xxx
    {
        private $conn;
    
        public function __construct($db_conn)
        {
            $this->conn = $db_conn;
        }
    
    
        function updateMaterial($code){
    
            $sql = $this->conn->prepare("UPDATE stock SET qty=qty+:incqty 
                                          WHERE WHERE itemcode = :code");
            $param = array(':incqty'=>$this->qty, ':code'=>$code);
            $sql->execute($param);
    
            if ( ! $sql ) {
                // while testing
                $arr = $sql->errorInfo();
                print_r($arr);
                exit;
            }      
        }
    

    Now when you instaniate the object pass the database connection handle

    $xxx = new xxx($conn);
    $xxx->qty = 30;
    $xxx->updateMaterial($code);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?