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 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真