I'm trying to prevent the user from purchasing any share, if the cash in his/her account is less than the desired stock cost (price * shares). However, I'm getting the following error:
Warning: mysql_query() expects parameter 1 to be string, array given in /home/jharvard/vhosts/pset7/public/buy.php on line 39
Here is the script:
<?php
// include configuration file
require("../includes/config.php");
// check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if symbol or share is empty
if (empty($_POST["symbol"]) || empty($_POST["shares"]))
{
// display error message
apologize("Symbol and Stock must not be empty.");
}
// check if symbol is valid
if (lookup($_POST["symbol"]) === false)
{
// display error message
apologize("Invalid stock symbol.");
}
// ensure that shares are only positive integers
if (preg_match("/^\d+$/", $_POST["shares"]) == false)
{
// display error message
apologize("Only a whole number is allowed.");
}
// set the transaction type to display in history
$transaction = 'Bought';
if ($stock = lookup($_POST["symbol"]))
{
// calculate total cost (ie shares * price)
$cost = $_POST["shares"] * $stock["price"];
$cash = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
$viewchk = mysql_query($cash);
$arrchk = $viewchk;
if ($arrchk["cash"] < $cost)
{
// display error message
apologize("You don't have enough funds to buy this share.");
}
// if user's cash >= cost of share, allow purchase
else
{
// ensure symbols are saved in DB in uppercase
$_POST["symbol"] = strtoupper($_POST["symbol"]);
query("INSERT INTO portfolios (id, symbol, shares) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)", $_SESSION["id"], $_POST["symbol"], $_POST["shares"]);
query("UPDATE users SET cash = cash - ? WHERE id = ?", $cost, $_SESSION["id"]);
query("INSERT INTO history (id, transaction, symbol, shares, price) VALUES (?, ?, ?, ?, ?)", $_SESSION["id"], $transaction, $_POST["symbol"], $_POST["shares"], $stock["price"]);
// redirect to homepage
redirect("/");
}
}
}
else
{
render("buy_form.php", ["title" => "Buy Stock"]);
}
?>