in the database I'm working with, there's a table named "packets", in this table there are columns like "id", "userid" etc. and a column named "usage"(I know its a poor choice of name cause usage is a reserved word, but sadly I may not change anything in the table), the type of this column is enum with 3 values("education", "study" and "advanced training") with "education" as default-value and the value can be NULL.
I wrote a class Packet with getters/setters like set_usage($usage)/get_usage()
and a class Packet_dao for accessing database using pdo:
class Packet_dao {
private m_insert_query;
...
public function persist($data)
{
$query = $this->m_insert_query;
try
{
$stmt = $this->bind_param($data, $query);
$stmt->execute();
return true;
}
catch (PDOException $ex)
{
$this->m_error_message = $ex->getMessage();
return false;
}
}
private function bind_param($packet, $query)
{
$stmt = $this->m_pdo->prepare($query);
$stmt->bindParam(':userId', $packet->get_user_id());
...
$stmt->bindParam(':usage', $packet->get_usage());
return $stmt;
}
insert query would looks like
INSERT INTO packets (userId, number, ..., `usage`)
VALUES (:userId, Coalesce(:number, default(number)), Coalesce(:usage, default(`usage`)))
so if I want to add a packet into db, the code would looks like:
$packet = new Packet();
$packet_dao = new Packet_dao();
$packet->set_stuff("stuff");
$packet_dao->persist($packet);
so far, so good, everything is working fine.
now, another usage-case "fullversion" should be added, and instead of adding a new value to the enum, they decided to use NULL as value of usage for packets which are full version. Now I get a problem: when I try to set value for usage using $packet->set_usage(NULL)
, it will be interpreted as the same as if the value isn't set and the default value("education") will be set in this case. What should I do?
apparently, the 2nd parameter of Coalesce() force it to take the default value when nothing is set (or NULL), after I changed Coalesce(:usage, default(usage))
into :usage
. It worked
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.