Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else statement with mysql table? - PHP

I need to make an if else statement that will prevent a user from bidding on an item if they are the highest bidder. I think it would go a little something like this.

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());
}
?>

I'm not sure how to reference the accountid from the bidhistory table. Also, if there is a better way to do this, please point me in the wright direction. Thanks!

like image 428
Lulu Sparks Avatar asked Jun 25 '26 18:06

Lulu Sparks


1 Answers

Note:

  • You can fetch the row of the highest bid with the specific item first. Then check if the highest bidder (accountid) is the same with the current user.
  • You can check the notes I had for some lines quoted in /* ... */

Your query for checking:

$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 */
}

But I recommend that you use mysqli_* rather than the 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 */
like image 110
Logan Wayne Avatar answered Jun 27 '26 07:06

Logan Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!