I have a class, and within that class, I have a function to update a data in the MySQL database. Here is the function:
public function set_detail($id, $detail, $value) {
$query = "UPDATE 'contacts' SET $detail = '$value' WHERE 'contact'.'id' = $id";
if (parent::do_sql($query)) {
return true;
} else {
return false;
}
}
So far so good. But the problem is in the '$value'
variable. If the value received via $_POST
is NULL
, '$value'
receives an empty string ''
and thus is sent to the database.
I assumed this happened because of the single quotes around the variable. So I removed the quotation marks and when trying to query again, I get the syntax error:
Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE 'contacts'.'id' = 0000000839'
I also assumed that it was for removing the quotation marks. But I've written MySQL queries without quotation marks and they worked fine.
What I do not want is to leave empty strings in the database. How to solve this? Which way is right?