我有 sell.php 和一个 sell_form.php 文件。他们在销售方面工作良好,但如果他们为股票代码选择空值,我想尝试向用户发送错误消息。我已经实施
'if(["blank"]){
apologize("You must select a stock symbol");
}'
我收到这条 if 语句的错误消息,但我也无法出售选定的股票。我不知道我在哪里犯了错误。我也尝试使用这个 if 语句
'if([empty($_POST["symbol"])){
apologize("You must select a stock symbol");
}'
这会将我重定向到没有错误的主页。任何帮助,将不胜感激。这是我的两个文件的代码。出售.php
//configuration
require("../includes/config.php");
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["symbol"])){
apologize("You must select a stock symbol");
}
// lookup stock
$stock = lookup($_POST["symbol"]);
// lookup user's shares of stock being sold
$shares = query("SELECT shares FROM shares WHERE id = ? AND symbol = ?", $_SESSION["id"], $_POST["symbol"]);
// calculate total sale value (stock's price * shares)
$value = $stock["price"] * $shares[0]["shares"];
$date = date("Y-m-d, H:i:s");
// add the sale value to cash
query("UPDATE users SET cash = cash + ? WHERE id = ?", $value, $_SESSION["id"]);
// delete the stock from their portfolio
query("DELETE FROM shares WHERE id = ? AND symbol = ?", $_SESSION["id"], $_POST["symbol"]);
query("INSERT INTO history (id, symbol, soldOrBought, numberOfSharesBoughtOrSold, price, dateAndTime)
VALUES (?, ?, 'Sold', ?, ?, ?)", $_SESSION["id"], strtoupper($_POST["symbol"]), $shares[0]["shares"], $stock["price"], $date );
redirect("/");
}
else
{
$rows = query("SELECT * FROM shares WHERE id = ?", $_SESSION["id"]);
//create array to store the shares
$shares = [];
//for each of the user info
foreach($rows as $row){
//lookup stock info
$stock = lookup($row["symbol"]);
if($stock !== false){
$shares[] = [
"name" => $stock["name"],
"price" => $stock["price"],
"shares" => $row["shares"],
"symbol" => $row["symbol"],
"total" => $row["shares"]*$stock["price"]
];
}
}
// render portfolio
render("sell_form.php", ["shares" => $shares, "title" => "Sell"] );
}
?>
出售表格.php
<ul class="nav nav-pills" >
<li >
<a href="index.php">Portfolio</a>
</li>
<li>
<a href="quote.php">Quote</a>
</li>
<li>
<a href="buy.php">Buy</a>
</li>
<li>
<a href="sell.php">Sell</a>
</li>
<li>
<a href="history.php">History</a>
</li>
<li>
<a href="deposit.php">Deposit Funds</a>
</li>
</ul>
<form action="sell.php" method="post">
<fieldset>
<div class="control-group">
<select name="symbol">
<option value="blank"></option>
<?php foreach ($shares as $symbol):?>
<option value="<?= $symbol["symbol"]?>"><?= $symbol["symbol"]?></option>
<? endforeach ?>
</select>
</div>
<div class="control-group">
<button type="submit" class="btn">Sell all shares</button>
</div>
</fieldset>
</form>
<div>
or <a href="logout.php">log out</a>
</div>