tironci
tironci

Reputation: 217

cannot compare query result in php

I am trying to compare a query result for available cash with a stock price but it is not working and I do not understand why. I do not understand why it is not working since it seems that they $cash and $value are valid numbers. This is the line that is giving me the problem.

if($cash < $value)

this is the whole file

<?php

//configuration
require("../includes/config.php");



//query user's portfolio
if ($_SERVER["REQUEST_METHOD"] == "POST") 
{

    // Insert the stock into their portfolio 
    if(preg_match("/^\d+$/", $_POST["shares"])==false){

        apologize("Please enter full share numbers");

    }else{

    $cash = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);

    // lookup stock
    $stock = lookup($_POST["symbol"]);

    // calculate total sale value (stock's price * shares)
    $value = $stock["price"] * $_POST["shares"];

    if($cash < $value){
        apologize("you do not have enough money");
    }else{


         //insert stock into database      
       query("INSERT INTO shares 
           (id, symbol, shares)
           VALUES (?, ?, ?) 
           ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)",
           $_SESSION["id"], strtoupper($_POST["symbol"]),$_POST["shares"]
             );  

        // substract the share value from cash
        query("UPDATE users SET cash = cash - ? WHERE id = ?", $value, $_SESSION["id"]);

        redirect("/");
      }

    }
}
else
{


// render portfolio
render("buy_search.php", ["title" => "Buy"] );
}
?>

This is the query function

function query(/* $sql [, ... ] */)
{
    // SQL statement
    $sql = func_get_arg(0);

    // parameters, if any
    $parameters = array_slice(func_get_args(), 1);

    // try to connect to database
    static $handle;
    if (!isset($handle))
    {
        try
        {
            // connect to database
            $handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);

            // ensure that PDO::prepare returns false when passed invalid SQL
            $handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
        }
        catch (Exception $e)
        {
            // trigger (big, orange) error
            trigger_error($e->getMessage(), E_USER_ERROR);
            exit;
        }
    }

    // prepare SQL statement
    $statement = $handle->prepare($sql);
    if ($statement === false)
    {
        // trigger (big, orange) error
        trigger_error($handle->errorInfo()[2], E_USER_ERROR);
        exit;
    }
    // execute SQL statement
    $results = $statement->execute($parameters);
    // return result set's rows, if any
    if ($results !== false)
    {
        return $statement->fetchAll(PDO::FETCH_ASSOC);
    }
    else
    {
        return false;
    }
}

Upvotes: 1

Views: 238

Answers (2)

David Chan
David Chan

Reputation: 7505

$cash is almost certainly not a number, or even a scalar value.

query probably returns an array of result objects, or arrays.

Upvotes: 0

kittycat
kittycat

Reputation: 15044

if ($cash[0]['cash'] < $value)

According to your debugging comment, it should be this as you need to access the array index cash of the array index 0. If you do not want this format, you should look into how your query results are returned to not have to use nested arrays.

Upvotes: 1

Related Questions