PHP: Update multiple MySQL fields in single query

后端 未结 4 1563
清歌不尽
清歌不尽 2020-12-05 08:09

I am basically just trying to update multiple values in my table. What would be the best way to go about this? Here is the current code:

$postsPerPage = $_PO         


        
相关标签:
4条回答
  • 2020-12-05 08:38

    Add your multiple columns with comma separations:

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

    However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

    Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

    0 讨论(0)
  • 2020-12-05 08:44

    Comma separate the values:

    UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"
    
    0 讨论(0)
  • 2020-12-05 08:58

    I guess you can use:

    $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();
    
    0 讨论(0)
  • 2020-12-05 09:00

    If you are using pdo, it will look like

    $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));
    
    0 讨论(0)
提交回复
热议问题