douhui3760 2017-01-20 00: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.

  1. function updateMaterial($code){
  2. global $conn;
  3. $sql = $conn->prepare("SELECT * FROM stock WHERE itemcode = '$code'");
  4. $sql->execute();
  5. while($row = $sql->fetch(PDO::FETCH_ASSOC)){
  6. $this->id = $row['id'];
  7. }
  8. if(isset($_POST['qty'])){
  9. $sql = $conn->prepare("UPDATE stock SET qty='qty +$this->qty' WHERE id='$this->id'");
  10. $sql->execute();
  11. }
  12. }
  13. if(isset($_POST['update'])){
  14. $code = $_POST['itemcode'];
  15. if($addstock->updateMaterial($code)){
  16. return true;
  17. }else{
  18. return false;
  19. }
  20. }
  • 写回答

1条回答 默认 最新

  • duankuai6586 2017-01-20 00: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

    1. class xxx
    2. {
    3. private $conn;
    4. public function __construct($db_conn)
    5. {
    6. $this->conn = $db_conn;
    7. }
    8. function updateMaterial($code){
    9. $sql = $this->conn->prepare("UPDATE stock SET qty=qty+:incqty
    10. WHERE WHERE itemcode = :code");
    11. $param = array(':incqty'=>$this->qty, ':code'=>$code);
    12. $sql->execute($param);
    13. if ( ! $sql ) {
    14. // while testing
    15. $arr = $sql->errorInfo();
    16. print_r($arr);
    17. exit;
    18. }
    19. }

    Now when you instaniate the object pass the database connection handle

    1. $xxx = new xxx($conn);
    2. $xxx->qty = 30;
    3. $xxx->updateMaterial($code);

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部