Add 1 to a field

前端 未结 7 1613
醉梦人生
醉梦人生 2021-02-06 23:58

How do I turn the following 2 queries into 1 query

$sql    = \"SELECT level FROM skills WHERE id = $id LIMIT 1;\";
$result = $db->sql_query($sql);
$level  = (         


        
7条回答
  •  -上瘾入骨i
    2021-02-07 00:35

    I get downmodded for this?

    $sql = "UPDATE skills SET level = level+1 WHERE id = $id";
    $result = $db->sql_query($sql);
    $db->sql_freeresult($result);
    

    In Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL.

    In the general case, you should not use NULL to represent zero. Incrementing NULL should give an answer of NULL. If you're the kind of misguided developer who thinks NULL=0, step away from keyboard and find another pastime, you're just making life hard for the rest of us. Of course, this is the computer industry and who are we to say you're wrong? If you're not wrong, use

    $sql = "UPDATE skills SET level = COALESCE(level,0)+1 WHERE id = $id";
    

    ...but let's face it: you're wrong. If everyone starts at level 0, then your DDL should include

    level INT DEFAULT '0' NOT NULL
    

    in case the programmers forget to set it when they create a record. If not everyone starts on level 0, then skip the DEFAULT and force the programmer to supply a value on creation. If some people are beyond levels, for whom having a level is a meaningless thing, then adding one to their level equally has no meaning. In that case, drop the NOT NULL from the DDL.

提交回复
热议问题