0

我有一个 MySQL 数据库。这包括各种表格,包括“会员”和“股票”。

我正在创建一个“股票交易游戏”,并想从用户当前拥有的余额中扣除股票成本。

我在股票表中有“价格”列,在成员表中有“余额”列。

单击按钮时,我希望从成员的余额中减去股票的价格。

老实说,我不知道如何做到这一点,但作为尝试,这里是我尝试过的代码,但实际上什么也没做:

if (isset($_POST['user']))
{
    $userselection = sanitizeString($_POST['userselection']);


    if ($userselection == "")
        $error = "Not all fields were entered<br /><br />";
    else
    {
            $stockprice = queryMysql("SELECT price FROM stocks WHERE name='$userselection'");
            $newbalance = ($balance - $stockprice);
            queryMysql("INSERT INTO members VALUES('', '', '', '', '', '', '$newbalance',  )");
            die("<h4>You just bought $userselection</h4><br /><br />");

    }
}

架构: 在此处输入图像描述

<?php 
include_once 'functions.php';

createTable('members',
            'id INT(50) NOT NULL AUTO_INCREMENT,
            firstname VARCHAR(100),
            surname varchar(100),
            user varchar(30),
            pass varchar(30),
            email varchar(100),
            balance float(12),
            PRIMARY KEY (id)');


createTable('stocks', 
            'id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(16),
            price float(16)');

createTable('profiles',
            'user VARCHAR(16),
            text VARCHAR(4096)');

?>
4

2 回答 2

0

UPDATE members m join stocks s on s.id = m.stock_id where m.balance = m.balance - s.price

如果您要将架构发布为小提琴,我实际上可以测试此查询。

于 2013-05-01T00:33:33.113 回答
0

一般来说:

UPDATE Members
INNER JOIN Stocks ON Stocks.Name = '<name-of-stock>'
SET balance = balance - Stocks.price * <number-of-stocks>
WHERE Members.ID = <member-id>

使用mysqli与数据库交互。它更安全。这是一个例子;除了数据库连接信息之外,您还需要提供股票名称、股票数量和会员 ID,但即使您不使用 mysqli,您也需要执行所有这些操作:

$sql = <<< ENDSQL
  UPDATE Members
    INNER JOIN Stocks ON Stocks.Name = ?
    SET balance = balance - Stocks.price * ?
    WHERE Members.ID = ?
ENDSQL

$stockName = '<the stock name>';
$numStocks = <number of stocks>;
$memberId = <member ID>;

$conn = new mysqli('hostname', 'username', 'pass', 'database if needed');
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'sdi', $stockName, $numStocks, $memberId);
mysqli_stmt_execute($stmt);
于 2013-05-01T00:58:28.343 回答