如果用mysql表声明else? - PHP

时间:2015-07-14 03:05:41

标签: php mysql if-statement

我需要制作一个if else语句,以阻止用户在项目出价最高时对其进行出价。我认为这会有点像这样。

if ($accountid = the accountid in the bidhistory table)
{
    echo "You are the highest bidder!";

}
else
{
$sql="INSERT INTO bidhistory (accountid, biditemid)
VALUES ($accountid, $itemid)"; 

mysql_query("
UPDATE bidhistory
SET bidprice = bidprice + 1
WHERE biditemid = " .
@mysql_escape_string($itemid));

$result=mysql_query($sql) or die("Error in adding bid for item: ".mysql_error());
}
?>

我不确定如何从bidhistory表中引用accountid。此外,如果有更好的方法,请指出我在正确的方向。谢谢!

1 个答案:

答案 0 :(得分:2)

注意:

  • 您可以先使用特定项目获取最高出价的行。 然后检查出价最高者(accountid)是否与当前用户相同。
  • 您可以查看我对/* ... */
  • 中引用的某些行的注释

您的查询检查:

$result = mysql_query("SELECT accountid FROM bidhistory WHERE biditem = '$itemid' ORDER BY bidhistoryid DESC LIMIT 1"); /* GET THE LAST ROW FOR WHO BIDS LAST; AND REPLACE NECESSARY COLUMN NAME (unique/primary) - bidhistoryid */
while($row = mysql_fetch_array($result)){
  $checkaccountid = $row['accountid']; /* STORE THE USER THAT BIDS LAST FOR THIS ITEM */
}

if($checkaccountid == $accountid){ /* THEN COMPARE IT WITH THE CURRENT USER */
  /* CODE YOU WANT TO DO IF HE/SHE IS THE LAST BIDDER ALREADY */
}
else {
  /* IF NOT, HE/SHE CAN STILL BID */
}

但我建议您使用mysqli_*而不是deprecated mysql_* API。

$con = new mysqli("YourHost", "Username", "Password", "Database"); /* REPLACE NECESSARY DATA */

/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if($stmt = $con->prepare("SELECT accountid FROM bidhistory WHERE biditem = ? ORDER BY bidhistoryid DESC LIMIT 1")){  
  $stmt->bind_param("i",$itemid); /* BIND THIS VARIABLE TO YOUR QUERY ABOVE */
  $stmt->execute(); /* EXECUTE THE QUERY */
  $stmt->bind_result($checkaccountid); /* STORE THE RESULT TO THIS VARIABLE */
  $stmt->fetch(); /* FETCH THE RESULT */

  if($checkaccountid == $accountid){
    /* CODE YOU WANT TO DO IF HE/SHE IS THE LAST BIDDER ALREADY */
  }
  else {
    /* IF NOT, HE/SHE CAN STILL BID */
  }
  $stmt->close();

} /* END OF PREPARED STATEMENT */