【问题标题】:PHP: Update multiple MySQL fields in single queryPHP:在单个查询中更新多个 MySQL 字段
【发布时间】:2011-03-10 00:39:32
【问题描述】:

我基本上只是想更新表中的多个值。解决此问题的最佳方法是什么?这是当前代码:

$postsPerPage = $_POST['postsPerPage'];
$style = $_POST['style'];

mysql_connect ("localhost", "user", "pass") or die ('Error: ' . mysql_error());
mysql_select_db ("db");

mysql_query("UPDATE settings SET postsPerPage = $postsPerPage WHERE id = '1'") or die(mysql_error());

我想包含的另一个更新是:

mysql_query("UPDATE settings SET style = $style WHERE id = '1'") or die(mysql_error());

谢谢!

【问题讨论】:

    标签: php mysql sql sql-update


    【解决方案1】:

    使用逗号分隔添加多个列:

    UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'
    

    但是,您没有清理您的输入?这意味着任何随机黑客都可能破坏您的数据库。看到这个问题:What's the best method for sanitizing user input with PHP?

    另外,样式是数字还是字符串?我假设一个字符串,所以它需要被引用。

    【讨论】:

      【解决方案2】:

      逗号分隔值:

      UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"
      

      【讨论】:

      • 好的,但不赞成,因为您忘记指出这种方法的明显缺陷。 :)
      【解决方案3】:

      如果你使用的是 pdo,它看起来像

      $sql = "UPDATE users SET firstname = :firstname, lastname = :lastname WHERE id= :id";
      $query = $this->pdo->prepare($sql);
      $result = $query->execute(array(':firstname' => $firstname, ':lastname' => $lastname, ':id' => $id));
      

      【讨论】:

        【解决方案4】:

        我猜你可以使用:

        $con = new mysqli("localhost", "my_user", "my_password", "world");
        $sql = "UPDATE `some_table` SET `txid`= '$txid', `data` = '$data' WHERE `wallet` = '$wallet'";
        if ($mysqli->query($sql, $con)) {
            print "wallet $wallet updated";
        }else{
            printf("Errormessage: %s\n", $con->error);
        }
        $con->close();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-03
          相关资源
          最近更新 更多