PHP 通过 SELECT 设置变量,如果变量 <3 做某事,+1,然后更新数据库

PHP set variable via SELECT, if variable <3 do something, +1, then UPDATE database

在我的数据库中,我有 1 个 table 称为 'members'。这个 table 只有两个字段:'id' 和 'attempts'。 只有一行,'id'设置为1,'attempts'设置为0。

只要这个脚本是运行,我就想给table的'attempts'加1。 运行ning一次后'attempts'应为1,两次应为2等

我想将变量 $attempts 设置为 table 的 'attempts' 设置的值。

如果 $attempts 值为 3 或更多,我希望它回显 "something",然后将 table 的 'attempts' 值更改为 0。

这是我已有的,我该怎么做? 我是 php 的新手,正在阅读手册。任何提示或帮助表示赞赏。谢谢你们:)

$attempts = mysql_query("SELECT attempts FROM members WHERE id=1");

if (++$attempts >= 3) {
    echo "SUCCESS!!";
    $attempts = 0;
}else {
    echo "3 attempts haven't been made yet...";
}

$sql = "UPDATE members SET attempts='$attempts' WHERE id=1";

WHERE子句中添加条件并更改条件语句:

旁注:这当然是看到 "attempts" 列是一个 int 类型。

$attempts = mysql_query("SELECT attempts FROM members WHERE id=1 AND attempts >=3");

if($attempts) {
   echo "SUCCESS!!";
$attempts = 0;
}


else {
    echo "3 attempts haven't been made yet...";
}

$sql = mysql_query("UPDATE members SET attempts='$attempts' WHERE id=1");

旁注:您可能希望将更新放在 else{...}
并执行 SET attempts = attempts +1 将其增加 1
或重置为零 SET attempts='$attempts'.



编辑:

如 OP 所述(来自评论):

以上答案无效,因为 mysql_query 会导致 $attempts 回显资源 ID #3,而不是实际的 table 值。

但是,您可以改用 mysql_fetch_assoc 来解决此问题。

您需要添加的所有内容都在这里:link 我在下面包含了工作代码并选择它作为答案,因为它让我走上了正确的轨道。

非常感谢 Fred 帮助我。

$sql = "SELECT attempts FROM members WHERE id=1"; 
$result = mysql_query($sql); 
    while ($row = mysql_fetch_assoc($result)) { 
$attempts = $row["attempts"];
}

等..


编辑#2,测试

它检查 "attempts" 行是否大于 3。如果是,则将其重置为 0。

如果不是,则将与 "id" 相关的行增加 1。

<?php 
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';

$Link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($Link->connect_errno > 0) {
  die('Connection failed [' . $Link->connect_error . ']');
}

$query = mysqli_query($Link, "SELECT attempts FROM members WHERE id=1");

while ($row = mysqli_fetch_assoc($query)) {

if($row['attempts'] >=3) {
   echo "SUCCESS!!";
 $attempts = 0;

 $sql = mysqli_query($Link, "UPDATE members SET attempts='$attempts' WHERE id=1");

}

else {
    echo "More than 3 attempts haven't been made yet..., row has been incremented by 1.";

 $sql = mysqli_query($Link, "UPDATE members SET attempts= attempts +1 WHERE id=1");

    }

} // brace for while loop