简体   繁体   English

使用 PHP 在 Mysql 表中切换状态 - 最简单的方法

[英]Switch status in Mysql table with PHP - the easiest way

I have a Mysqli table called status with the columns ID, STATUS.我有一个名为 status 的 Mysqli 表,其列 ID 为 STATUS。

The STATUS can be 1 or 2 only. STATUS 只能是 1 或 2。

I want to update the STATUS column the easiest way, so if the STATUS value is 1, update it to 2 and vice versa.我想以最简单的方式更新 STATUS 列,因此如果 STATUS 值为 1,则将其更新为 2,反之亦然。

Normally I can do it like:通常我可以这样做:

 $c=$mysqli->query('SELECT * FROM status WHERE id="1"' );
    $kats=$c->fetch_assoc();
    $status=$kats['status'];

if ($status == '1') {$newstatus = '2';} else {$newstatus = '1';}

$mysqli->query("UPDATE status SET status = '$newstatus' WHERE id=1" );

This will work, but is there an easier way, or maybe 1 row query for this?这会起作用,但是有没有更简单的方法,或者可能是 1 行查询? As the values are just changing from 1 to 2 or from 2 to 1 in one column.因为值只是在一列中从 1 变为 2 或从 2 变为 1。

If you only have two values then consider using a Boolean data type.如果您只有两个值,请考虑使用 Boolean 数据类型。 If you do then you can do it in one query, something like this:如果你这样做了,那么你可以在一个查询中完成,如下所示:

UPDATE status SET STATUS = !STATUS WHERE ID = ?

Also, it's kinda confusing having status as both a table and column name.此外,将status同时作为表名和列名有点令人困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM