0
I have a class, and within this class, I have a function to update a data in the Mysql database. Follow 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 variable '$value'
. If the value received via $_POST
for NULL
, '$value'
takes an empty string ''
and so it is sent to the database.
I assumed this happened because of the single quotes around the variable. So I removed the quotes and while trying to perform the 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 it was because I removed the quotation marks. However I have already written queries in Mysql without quotation marks and worked normally.
What I don’t want is to leave empty strings in the database. How do I resolve this? What’s the right way?
I understand... But if you run the query directly in phpMyAdmin, SQL looks like this:
UPDATE 'contacts' SET 'phone' = NULL WHERE 'contacts'.'id' = 0000000839
. How to do this in function?– Pablo Degani
If you want it that way, just set the value of
$value
within theif
by "NULL", and use the query as it was before.– Vinicius Lourenço
I used this same logic, but within the function to mount the query. It was like this:
if (empty($value) || $value == "") { $query = "UPDATE 'contacts' SET $detail = NULL WHERE 'contacts'.'id' = $id"; } else { $query = "UPDATE 'contacts_business' SET $detail = '$value' WHERE 'contacts_business'.'id' = $id"; }
– Pablo Degani
That’s right. Just an addendum, you don’t need to compare
$value == ""
because the function itself already does this check. I leave here also another solution with the same question only asked in English.– Vinicius Lourenço