-1

我有 2 个问题: 1.我的问题是,当我尝试增加值时,它会重置回 1 ;2.我可以将我的代码简化为一个MYSQL语句(switch ... case代码)

public static function process($nr,$id) // (x,y,z,a,b ?) (the column id)
{

$х=$y=$z=$a=$b=0;

  switch ($nr) {
    case '1':
        $х=1;
        break;

        case '2':
        $y=1;
        break;

        case '3':
        $z=1;
        break;

        case '4':
        $a=1;
        break;

        case '5':
        $b=1;
        break;

  }




$conn = new PDO( DBN, DB_USER, DB_PASS );
$sql = "UPDATE test_table SET b=+:b, a=+:a,z=+:z,y=+:y,х=+:х WHERE id = :id";
$st = $conn->prepare ( $sql );
$st->bindValue( ":id", $id, PDO::PARAM_INT);
$st->bindValue( ":х", $х, PDO::PARAM_INT);
$st->bindValue( ":y", $y, PDO::PARAM_INT);
$st->bindValue( ":z", $z, PDO::PARAM_INT);
$st->bindValue( ":a", $a, PDO::PARAM_INT);
$st->bindValue( ":b", $b, PDO::PARAM_INT);
$st->execute();
$conn = null;
print_r($st->errorInfo());

}

4

2 回答 2

0
UPDATE table_name SET column_name = column_name+1 WHERE id = ?;

是增加任何数据库计数器的最佳方法,因为它是原子处理的,这意味着没有其他进程/线程可以意外插入先前读取的值,您 100% 确定每次调用函数/过程时都会增加该值。

如果你在 PHP 中做另一个——你会很糟糕——因为经典的竞争条件:

user1 -> read value // value=10
user2 -> read value // value=10
user1 -> write value++ // value becomes 11
user2 -> write value++ // value (AGAIN) becomes 11 but it should've been 12

为更复杂的查询避免这种情况涉及使用事务和特定的隔离级别。但事实上,由单个语句形成的所有 SQL 查询都是原子的。

于 2012-08-20T17:10:31.013 回答
-2

为什么不 ?

public static function process($nr,$id) // (x,y,z,a,b ?) (the column id)
{
$param;
switch ($nr) {
    case '1':
        $param = "x=x+1";
        break;

    case '2':
        $param = "y=y+1";
        break;

    case '3':
        $param = "z=z+1";
        break;

    case '4':
        $param = "a=a+1";
        break;

    case '5':
        $param = "b=b+1";
        break;

}

$conn = new PDO( DBN, DB_USER, DB_PASS );
$sql = "UPDATE test_table SET $param WHERE id = :id";
$st = $conn->prepare( $sql );
$st->bindValue( ":id", $id, PDO::PARAM_INT);
$conn = null;
print_r($st->errorInfo());

这也是我所有的 SQL 解决方案,如果你问我,我有点笨拙:

public static function process($nr,$id) // (x,y,z,a,b ?) (the column id)
{
    $sql <<<'EOD'
        UPDATE test_table SET
            x = CASE WHEN :nr = 1 THEN x + 1 ELSE x END CASE,
            y = CASE WHEN :nr = 2 THEN y + 1 ELSE y END CASE,
            z = CASE WHEN :nr = 3 THEN z + 1 ELSE z END CASE,
            a = CASE WHEN :nr = 4 THEN a + 1 ELSE a END CASE,
            b = CASE WHEN :nr = 5 THEN b + 1 ELSE b END CASE
        WHERE id = :id
     EOD;

     $conn = new PDO( DBN, DB_USER, DB_PASS );
     $st = $conn->prepare( $sql );
     $st->bindValue( ":nr", $nr, PDO::PARAM_INT);
     $st->bindValue( ":id", $id, PDO::PARAM_INT);
     $conn = null;
     print_r($st->errorInfo());
}
于 2012-08-20T16:53:40.383 回答