PHP MySQL选择字段并增加值


PHP MySQL select field and increment the value

我想获得指定字段的值(它是INT),然后增加这个值,然后在mysql中更新它。我试过了,但没用。我在MySQL中完全是绿色的。

            $attempts = mysql_fetch_array(mysql_query("SELECT attempts FROM employees WHERE lastname='$lastname'"));
            mysql_query("UPDATE employees SET attetmps='$attemtps++' WHERE lastname='$lastname'");

我建议:mysql_query("UPDATE employees SET attempts = attempts + 1 WHERE lastname = '".$lastname."'");

如果您想使用mysql_fetch_array,您应该知道它返回的是一个数组,而不是一个值

所以试试这个

<?php
$query = mysql_query("SELECT attempts FROM employees WHERE lastname='$lastname'");
$row = mysql_fetch_array($query, MYSQL_ASSOC);
$attempts = $row['attempts'] + 1;
mysql_query("UPDATE employees SET attempts='$attempts' WHERE lastname='$lastname'");
?>

或使用一个查询。。您不需要执行两个查询

mysql_query("
    UPDATE employees
    SET attempts = attempts + 1
    WHERE lastname = '".$lastname."'
");
UPDATE employees SET attempts = attempts + 1 WHERE lastname = '$lastname'