Dude22 Posted March 31, 2013 Share Posted March 31, 2013 Hi, I am currently working on completing an online computer science course, and am in the last few weeks, with just a few programs left, but that said time is of the essence. What I am working on right now is a program that will let you buy and sell stocks. No transactions actually occur, it only looks like you are buying and selling. I was given a framework to start with, here I have linked to a example completed project: http://finance.cs50.net/login.php I am getting close, but am having some trouble with the "buy" function. Here is my php code for buy: <?php // configuration require("../includes/config.php"); // if form was submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { if (((empty($_POST["symbol"])) == True) || ((empty($_POST["shares"])) == True)) { apologize("You MUST enter the Symbol, and ammount of stock that you want!"); } else if (preg_match("/^\d+$/", $_POST["shares"]) == False) { apologize("You must enter a postive whole number for the number of shares you want to buy!"); } else { $stock = lookup($_POST["symbol"]); $rows = query("SELECT LAST_INSERT_ID() AS id"); $id = $rows[0]["id"]; INSERT INTO table (id, symbol, shares) VALUES(7, , 10) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares) redirect("index.php"); } } else { // else render form render("buy_stock.php", ["title" => "Buy "]); } ?> And here is the code for the html front page of buy: <form action="buy.php" method="post"> <fieldset> <div class="control-group"> <input autofocus name="symbol" placeholder="SYMBOL" type="text"/> </div> <div class="control-group"> <input name="shares" placeholder="Number of shares" type="int"/> </div> <div class="control-group"> <button type="submit" class="btn">BUY</button> </div> </fieldset> </form> <div> or <a href="index.php">Home Page</a> </div> Here is a program defining functions, this program was provided buy the course: <?php /*********************************************************************** * functions.php * * Computer Science 50 * Problem Set 7 * * Helper functions. **********************************************************************/ require_once("constants.php"); /** * Apologizes to user with message. */ function apologize($message) { render("apology.php", ["message" => $message]); exit; } /** * Facilitates debugging by dumping contents of variable * to browser. */ function dump($variable) { require("../templates/dump.php"); exit; } /** * Logs out current user, if any. Based on Example #1 at * http://us.php.net/manual/en/function.session-destroy.php. */ function logout() { // unset any session variables $_SESSION = array(); // expire cookie if (!empty($_COOKIE[session_name()])) { setcookie(session_name(), "", time() - 42000); } // destroy session session_destroy(); } /** * Returns a stock by symbol (case-insensitively) else false if not found. */ function lookup($symbol) { // reject symbols that start with ^ if (preg_match("/^\^/", $symbol)) { return false; } // reject symbols that contain commas if (preg_match("/,/", $symbol)) { return false; } // open connection to Yahoo $handle = @fopen("http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s=$symbol", "r"); if ($handle === false) { // trigger (big, orange) error trigger_error("Could not connect to Yahoo!", E_USER_ERROR); exit; } // download first line of CSV file $data = fgetcsv($handle); if ($data === false || count($data) == 1) { return false; } // close connection to Yahoo fclose($handle); // ensure symbol was found if ($data[2] === "0.00") { return false; } // return stock as an associative array return [ "symbol" => $data[0], "name" => $data[1], "price" => $data[2], ]; } /** * Executes SQL statement, possibly with parameters, returning * an array of all rows in result set or false on (non-fatal) error. */ 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; } } /** * Redirects user to destination, which can be * a URL or a relative path on the local host. * * Because this function outputs an HTTP header, it * must be called before caller outputs any HTML. */ function redirect($destination) { // handle URL if (preg_match("/^https?:\/\//", $destination)) { header("Location: " . $destination); } // handle absolute path else if (preg_match("/^\//", $destination)) { $protocol = (isset($_SERVER["HTTPS"])) ? "https" : "http"; $host = $_SERVER["HTTP_HOST"]; header("Location: $protocol://$host$destination"); } // handle relative path else { // adapted from http://www.php.net/header $protocol = (isset($_SERVER["HTTPS"])) ? "https" : "http"; $host = $_SERVER["HTTP_HOST"]; $path = rtrim(dirname($_SERVER["PHP_SELF"]), "/\\"); header("Location: $protocol://$host$path/$destination"); } // exit immediately since we're redirecting anyway exit; } /** * Renders template, passing in values. */ function render($template, $values = []) { // if template exists, render it if (file_exists("../templates/$template")) { // extract variables into local scope extract($values); // render header require("../templates/header.php"); // render template require("../templates/$template"); // render footer require("../templates/footer.php"); } // else err else { trigger_error("Invalid template: $template", E_USER_ERROR); } } ?> I have been working on getting BUY working for the whole day, but have had nothing but errors... Does anything jump out as a problem to anyone??? If I haven't given you enough info, please let me know! Thanks in advance, I really am stuck on this one, and am running out of time, as this is not my last program. Josh Quote Link to comment Share on other sites More sharing options...
ignace Posted March 31, 2013 Share Posted March 31, 2013 $stock = lookup($_POST["symbol"]); $rows = query("SELECT LAST_INSERT_ID() AS id"); $id = $rows[0]["id"]; INSERT INTO table (id, symbol, shares) VALUES(7, , 10) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares) redirect("index.php");The INSERT INTO should be in the query() function. Quote Link to comment Share on other sites More sharing options...
Dude22 Posted March 31, 2013 Author Share Posted March 31, 2013 (edited) sorry, I am not quite sure what you are getting at... I made some changes to the code, and It now runs without any errors, but it doesn't add anything to the table either! Here is that code: <?php // configuration require("../includes/config.php"); // if form was submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { if (((empty($_POST["symbol"])) == True) || ((empty($_POST["shares"])) == True)) { apologize("You MUST enter the Symbol, and ammount of stock that you want!"); } else if (preg_match("/^\d+$/", $_POST["shares"]) == False) { apologize("You must enter a postive whole number for the number of shares you want to buy!"); } else { $stock = lookup($_POST["symbol"]); $rows = query ("SELECT LAST_INSERT_ID() AS id"); $id = $rows[0]["id"]; "INSERT INTO portfolio (id, symbol, shares) VALUES ('11','$stock[symbol]','$_POST[shares]')"; //ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)) redirect("index.php"); } } else { // else render form render("buy_stock.php", ["title" => "Buy "]); } ?> Edited March 31, 2013 by Dude22 Quote Link to comment Share on other sites More sharing options...
Jessica Posted March 31, 2013 Share Posted March 31, 2013 You just have a random string, you didn't actually execute it. Quote Link to comment Share on other sites More sharing options...
Dude22 Posted April 1, 2013 Author Share Posted April 1, 2013 Sorry, I really don't understand what you are saying, I have looked over all the code, and can't find what you are referencing. I also looked at a few tutorials for adding information into an sql table, and as far as I can tell, they do nothing that I don't. Quote Link to comment Share on other sites More sharing options...
RobertP Posted April 1, 2013 Share Posted April 1, 2013 I think you should be reading the material the course is providing. Quote Link to comment Share on other sites More sharing options...
Dude22 Posted April 1, 2013 Author Share Posted April 1, 2013 (edited) Below is everything the course provides for "buy": Now it's time to support actual buys. Implement the ability to buy, with a controller called, say, buy.php and some number of templates. (As before, you need not worry about interruptions of service or race conditions.) The interface with which you provide a user is entirely up to you, though, as before, feel free to look to https://x.cs50.net/finance for inspiration or hints. Of course, you'll need to ensure that a user cannot spend more cash than he or she has on hand. And you'll want to make sure that users can only buy whole shares of stocks, not fractions thereof. For this latter requirement, know that a call like preg_match("/^\d+$/", $_POST["shares"]) will return true if and only if $_POST["shares"] contains a non-negative integer, thanks to its use of a regular expression. See http://www.php.net/preg_match for details. Take care to apologize to the user if you must reject their input for any reason. In other words, be sure to perform rigorous error-checking. (We leave to you to determine what needs to be checked!) When it comes time to store stocks' symbols in your database table, take care to store them in uppercase (as is convention), no matter how they were inputted by users, so that you don't accidentally treat, say, dvn.v and DVN.V as different stocks. Don't force users, though, to input symbols in uppercase. Incidentally, if you implemented your table for users' portfolios as we did ours (with that joint primary key), know that SQL like the below (which, unfortunately, wraps onto two lines) will insert a new row into table unless the specified pair of id and symbol already exists in some row, in which case that row's number of shares will simply be increased (say, by10). INSERT INTO table (id, symbol, shares) VALUES(7, 'DVN.V', 10) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares) As always, be sure to bang on your code. And be sure that your HTML is valid! As far as I can tell, there is nothing that helps me with my current problem... Edited April 1, 2013 by Dude22 Quote Link to comment Share on other sites More sharing options...
ignace Posted April 1, 2013 Share Posted April 1, 2013 Sorry, I really don't understand what you are saying, I have looked over all the code, and can't find what you are referencing. I also looked at a few tutorials for adding information into an sql table, and as far as I can tell, they do nothing that I don't.This also clearly shows that you did not write the above code (which even uses PHP 5.4 syntax) because it would be really weird (or amnesia) that you would know how to execute a query at one point and not at the second. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.