1

我正在用 PHP 和 SQL 创建一个股票交易游戏。我有一个“购买”功能,可将股票 ID、用户 ID 和数量添加到名为“ownedstocks”的表中。

我在执行一个简单的“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/>");

            ?>
4

3 回答 3

1

您想要的是 MySQL INSERT INTO ON DUPLICATE KEY UPDATE功能。

基本上:

INSERT INTO ownedstocks values (...) ON DUPLICATE KEY UPDATE amount = amount + '$amount'
于 2013-05-02T19:34:25.143 回答
0

您可以使用 mysqli.affected-rows 变量http://php.net/manual/en/mysqli.affected-rows.php来实现 IF 语句。

于 2013-05-02T19:38:06.267 回答
0

user在 ( , )上添加唯一性stock_id

ALTER TABLE `ownedstocks` ADD UNIQUE (
    `user` ,
    `stock_id`
);

然后执行以下操作:

INSERT INTO ownedstocks
VALUES ('$user', '$id', '$amount')
ON DUPLICATE KEY UPDATE
`amount` = `amount` + '$amount';
于 2013-05-02T19:36:52.097 回答