0

I want to make an easy function inside a class that can update each cell in a database.

Like I now can use echo $user->cell('email'); to retrieve the email, I want to update it with

$user->update('email','new@email.com');

But for as far as I know, bind_param() doesn't support "?=?" in the query. Anybody a safe solution to that?

class User{
    private $details;
    private $id;
    function __construct($userId){
        $db = Database::getInstance();
        $mysqli = $db->getConnection();
        $stmt = $mysqli->prepare("SELECT * FROM users WHERE id=?");
        $stmt->bind_param("i",$userId);
        $stmt->execute();
        $result = $stmt->get_result();
        if($result->num_rows == 1){
            $this->details = $result->fetch_assoc();
            $GLOBALS['userId'] = $userId;
        }
        $stmt->close();
    }
    function cell($cell){
        return $this->details[$cell];
    }
    function update($cell,$value){
        $db = Database::getInstance();
        $mysqli = $db->getConnection();
        $stmt = $mysqli->prepare("UPDATE users SET ?=? WHER id=".$this->id);
        $stmt->bind_param("ss",$cell,$value);
        $stmt->execute();
        return true;
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Bjorn T
  • 33
  • 8
  • 2
    you could just have a list of valid column names in your class properties and check from there – Kevin Aug 18 '20 at 06:33
  • 1
    You attempt to safely bind the column name, but you plainly concatenate the `"... id=" . $this->id`…!? – deceze Aug 18 '20 at 06:35
  • Kevin, you mean like set that column names in an array, just like what I did for the details? – Bjorn T Aug 18 '20 at 06:36
  • @BjornT yep, just declare them as an array – Kevin Aug 18 '20 at 06:52
  • this update method is not efficient. it should accept an array of cell-value pairs. this way it will be able to update either a single pair or multiple columns at once – Your Common Sense Aug 18 '20 at 09:29

0 Answers0