我有两个问题: 我的问题是,当我尝试增加值时,重置为1; 2.我可以将代码缩减为MYSQL语句(交换机...案例代码)
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());
}
答案 0 :(得分: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查询都是原子的。
答案 1 :(得分:-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());
}