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 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable