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

What you want is the MySQL INSERT INTO ON DUPLICATE KEY UPDATE function.

Basically:

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