我正在用PHP和SQL創建股票交易遊戲。我有一個'購買'功能,將股票ID,用戶ID和數量添加到名爲'ownedstocks'的表中。使用PHP和SQL的IF-ELSE
我在執行簡單的「If-Else」聲明時遇到了麻煩。 基本上,我想:
If the user id and the stock id of the stock being purchased are already exists in 'ownedstocks' table, then I just want to update the quantity. Else if no rows exist for the given user id and stock id, then I want to insert a new row.
我的代碼,但不確定使用IF-ELSE的。
在此先感謝!
<?php
include_once 'header.php';
$user = $_SESSION['user'];
$id = $_SESSION['id'];
$price = $_SESSION['price'];
$amount=$_POST['amount'];
$total = $amount*$price;
$balance = $_SESSION['balance'];
$con=mysqli_connect("localhost","root","usbw","stocktrading");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$newbalance = ($balance - $total);
queryMysql("UPDATE ownedstocks
SET quantity = (quantity+$amount)
WHERE ownedstocks.userid = '$user' and ownedstocks.stockid = '$id'");
queryMysql("INSERT INTO ownedstocks
VALUES ('$user', '$id', '$amount')");
queryMysql("UPDATE members
SET balance = $newbalance
WHERE members.user = '$user'");
echo("You just purchased $id costing $price per stock<br/><br/>
You bought $amount stocks<br/><br/>
To calculate your bill: $price x $amount which equals $total<br/><br/>
You have just spent $total, your new balance is $newbalance <br/><br/>");
?>
這工作奇蹟,謝謝!但只有一次我添加了一個索引; CREATE UNIQUE INDEX user_stock ON ownedstocks(userid,stockid); 謝謝! – MalvEarp 2013-05-02 20:15:00