Add 1 to a field

前端 未结 7 1606
醉梦人生
醉梦人生 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条回答
  • 2021-02-07 00:20

    With PDO and prepared query:

    $query = $db->prepare("UPDATE skills SET level = level + 1 WHERE id = :id")
    $query->bindValue(":id", $id);
    $result = $query->execute();
    
    0 讨论(0)
  • 2021-02-07 00:28

    Mat: That's what pasted in from the question. It hasn't been edited, so I attribute that to a bug in Markdown. But, oddly enough, I have noticed.

    Also: yes, mysql_escape_string()!

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-07 00:41

    How about:

    UPDATE skills SET level = level + 1 WHERE id = $id;
    
    0 讨论(0)
  • 2021-02-07 00:45

    $sql = "UPDATE skills SET level = level + 1 WHERE id = $id";

    I just hope you are properly sanitising $id elsewhere in your code!

    0 讨论(0)
  • 2021-02-07 00:47

    This way:

    UPDATE skills
    SET level = level + 1
    WHERE id = $id
    
    0 讨论(0)
提交回复
热议问题