来自table1的MySQLi查询和更新详细信息到table2

时间:2018-01-20 10:17:39

标签: php mysql mysqli

我几周都痴迷于以下问题,无法找到解决方案:

我有两个数据库表。我想用MySQLi查询从第一行中选择一行,从另一行中选择更多行。 第一个名为'users'的表,这里我存储了用户当前的货币信息。第二个表存储有关其'pets'的信息。 我到目前为止......但我也希望通过点击提交来更新宠物的一条信息。

所以这是我的代码:

$statement = $mysqli->prepare("SELECT money FROM users WHERE fbid = ?");
  $statement->bind_param("s", $_SESSION['FBID']);
  $statement->execute();
  $statement->bind_result($money);
  while ($statement->fetch());
  $statement->close();

if($stmt = $mysqli->prepare("SELECT clean,health,petname FROM pets WHERE fbid = ?")){

   $stmt->bind_param('s',$_SESSION['FBID']);

   $stmt->execute();

   $stmt->store_result();

   $num_of_rows = $stmt->num_rows;

   $stmt->bind_result($clean,$health,$petname);

   while ($stmt->fetch()) {

        if($_GET['buy']=='clean' && $money>='5' && $clean<='95'){
  $stmt2 = $mysqli->prepare("UPDATE pets SET `clean` = `clean` + 5 WHERE fbid = ? AND petname = ?");
  $stmt2->bind_param("ss", $_SESSION['FBID'],$_GET['identifier']);
  $stmt2->execute();
  $stmt2->close();
  $stmt3 = $mysqli->prepare("UPDATE users SET `money` = `money` - 5 WHERE fbid = ?");
  $stmt3->bind_param("s", $_SESSION['FBID']);
  $stmt3->execute();
  $stmt3->close();
            header( "Location: /pets.php?success=clean" );
        }
        if($_GET['buy']=='health' && $money>='7' && $health<='90'){
  $stmt4 = $mysqli->prepare("UPDATE pets SET `health` = `health` + 10 WHERE fbid = ? AND petname = ?");
  $stmt4->bind_param("ss", $_SESSION['FBID'],$_GET['identifier']);
  $stmt4->execute();
  $stmt4->close();
  $stmt5 = $mysqli->prepare("UPDATE users SET `money` = `money` - 7 WHERE fbid = ?");
  $stmt5->bind_param("s", $_SESSION['FBID']);
  $stmt5->execute();
  $stmt5->close();
            header( "Location: /pets.php?success=health" );
        }

echo "".$petname." welcomes you!<br>";      
if($health<='90' && $money>='7'){
echo "<form method='GET'><input type='hidden' name='identifier' value='".$petname."'><input type='hidden' name='buy' value='health'><input type='submit' value='Healthcare (G$7)'></form>";
}
if($clean<='95' && $money>='5'){
echo "<form method='GET'><input type='hidden' name='identifier' value='".$petname."'><input type='hidden' name='buy' value='clean'><input type='submit' value='Clean (G$5)'></form>";
}
   }

   $stmt->free_result();

   $stmt->close();
}

直到我点击提交才能完美运行。然后它会更新所选宠物的值,但它会像我拥有的​​宠物一样更新值。我想只更新一次,但我必须在一页中打印出所有宠物信息。

那我怎么能这样做呢?

(我无法使用get_result(),因为它未安装在服务器上!)

谢谢大家!

1 个答案:

答案 0 :(得分:1)

将更新宠物的逻辑与显示宠物的逻辑分开。您当前位于显示循环内,因此在显示循环的每次迭代中更新一只宠物。当您在while循环外移动更新代码时,您只会更新宠物信息一次,但仍然会循环显示所有宠物。