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"]);
    }

?>

Dani AI

Generated

The immediate error comes from calling mysql_query() with an array. In the posted code the CS50-style query(...) call returns an array of rows, which is then passed into mysql_query($cash) — PHP expects a SQL string, not an array, so the warning is thrown. 's suggestion to inspect session data is sensible if the session id might be malformed, but the primary bug here is the extra mysql_query call and the misuse of the SELECT result.

A minimal, focused fix is to read the SELECT result and compare the numeric values directly:

$rows = query("SELECT cash FROM users WHERE id = ?", $_SESSION['id']);
if (empty($rows)) { apologize("User not found."); }
$cash   = floatval($rows[0]['cash']);
$shares = intval($_POST['shares']);
$cost   = $shares * floatval($stock['price']);

if ($cash < $cost) { apologize("You don't have enough funds to buy this share."); }

Do not call mysql_query on $rows (or $cash) — the SELECT result is already returned as an array by the wrapper.

Additional recommendations (practical and durable):

  • Validate inputs strictly: confirm intval($_POST['shares']) > 0 or use filter_var(..., FILTER_VALIDATE_INT).
  • Avoid floating-point money errors: store/compute cents as integers or use a fixed-point library.
  • Don’t mix mysql_* functions with the query wrapper; use the same DB API (PDO/mysqli) throughout.
  • For concurrency safety, prefer an atomic update pattern such as UPDATE users SET cash = cash - ? WHERE id = ? AND cash >= ? and then check whether the update affected a row (or wrap the steps in a DB transaction).

If session id still looks odd after inspection, follow ’s var_dump idea (and inspect the shape of $rows) to ensure scalar IDs and expected array structure.

Could you do a var_dump on $_SESSION['id']? My guess is that it is an array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.