PHP - Post To Database Partial With Form
Hello,
I wrote a script where i can enter a stock symbol and it get saved in my database. This works, but when i enter the stock symbol i would like to also get the current stock price get saved into the database. The link for the stock price (i.e. AAPL): http://quote.yahoo.com/d/quotes.csv?s=AAPL&f=l1&e=.csv How do i programm this in the script below? Besides above, notice that "AAPL" in the link above has to be a varaible, which changes where i for example type in "GS". Form: Quote <html> <body> <form action="portfolio/insert_buy.php" method="post"> Symbol: <input type="text" name="symbol"><br /> <input type="submit" value=" Submit"> </form> </body> </html> PHP-script Quote <?php $conn = mysql_connect("xxx","xxx","xxx"); $db = mysql_select_db("xxx",$conn); $sql="INSERT INTO portfolio (symbol) VALUES ('$_POST[symbol]')"; if (!mysql_query($sql,$conn)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($conn); ?> I hope someone can help me out, thanks! Similar TutorialsOk .I tried to look for the problem for about 1 hour but I can't see what's wrong whit the following code: In firebug the post values appear correctly like so:id=116&usern=asdawe&com=qweqw&page=116&submit=submit and the inserc() function works correctly because i tried it whit a array of data created by my; Code: [Select] <?php if(isset($_POST['submit'])) { $comment = new comment; $comment->storeform($_POST); $comment->insertc(); } ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> <input type="hidden" name="id" value="<?php echo $result['article']->id ?>"/> <ul> <li> <input type="text" name="usern" id="usern" /> </li> <li> <textarea name="com" id="com" COLS=40 ROWS=6></textarea> </li> <input type="hidden" name="page" value="<?php echo $result['article']->id ?>" /> <input type="submit" name="submit" value="submit" /> </ul> </form> Code: [Select] <?php class comment{ public $id = null; public $usern = null; public $com = null; public $page = null; public function __construct($data=array() ) { if( isset($data['id']) ) $this->id= (int)$data['id']; if( isset($data['usern']) ) $this->usern= preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['usern'] ); if( isset($data['com']) ) $this->com= preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['com'] ); if( isset($data['page']) ) $this->page= (int)$data['page']; } public function storeform ( $params ) { // Store all the parameters $this->__construct( $params ); } public function insertc() { $con = new PDO(DBN,DB_USER,DB_PASS); $sql = "INSERT INTO comments (usern,com,page) VALUES (:usern,:com,:page)"; $st =$con->prepare($sql); $st->bindValue( ":usern", $this->usern, PDO::PARAM_STR ); $st->bindValue( ":com", $this->com, PDO::PARAM_STR ); $st->bindValue( ":page", $this->page, PDO::PARAM_INT ); $st->execute(); $this->id = $con->lastInsertId(); $con = null; } } ?> Hey Guys. I am working with a form that shows the grand total on the checkout page. The value of the grand total is inside a hidden field. When click on submit, the _POST array doesn't get back the last value of the grand total. I need to hit the button twice to get the last value. The weird thing is when I echo the value of the grand total it display the latest value, but not with the POST array
For example. If the grand total is $10.00 and I click on submit. It will show the POST['grand_total'] as empty. If I click on submit again it will show the grand total of $10.00.
Below is my code that I am working with. Any help would be really appreciated.
if(isset($_POST['submit'])) { /* Doesn't show if i put it after if($_POST['submit'] */ if(isset($_POST['grand_total'])) { echo $_POST['grand_total']; } } //A bunch of other html/php code. Another class calculates the subtotal assigns it the variable $subtotal $cart_totals = new cartTotals($subtotal, $discounted_amount,$post_values->tip); // Cart class is shown below /* Doesn't show if i put it before if($_POST['submit'] */ if(isset($_POST['grand_total'])) { echo $_POST['grand_total']; } echo "<input name='grand_total' type='hidden' value='$cart_totals->grand_total' />"; // Shows the grand total after second from submission echo "$cart_totals->grand_total"; // Shows grand total after the first submissionCart Totals Class class cartTotals { public $subtotal; public $sales_tax; public $tip; public $grand_total; public $discount_amount; public $href_page; public $invalidCouponMessage; const TEST_ENVIORMENT = FALSE; /** * [ Function gets constructed in the order summary where the [$discount_amount= ""] arg does need to be passed. * But does get passed in when called on the checkout.php page. Therefore we set the default value to an empty string.] * @param [float] $subtotal [subtotal get passed in from the parent class coreCartFunction] * @param string $discount_amount [The class checkCouponCode calculates this discount amount based on the * subtotal and the discount amount. It gets instantiated on the clients side and passed is this construction function. * This is all done on the checkout page.] */ /*The way the construct function works is by invoking all the methods the passed arguments When the methods get invoked the do all the work and set the properties its values. The properties then get echoed out on the client side. */ function __construct($subtotal="", $discount_amount= "", $tip=""){ $this->subTotal($subtotal, $discount_amount);//SubTotal method takes the discount amount and subtracts it from the subtotal. $this->salesTax($subtotal, $discount_amount); $this->tip = $tip; $this->grandTotal(); } private function subTotal($subtotal,$discount_amount) { $rounded_subtotal = round($subtotal-$discount_amount,2); $money_format_subtotal = money_format('%i',$rounded_subtotal); $this->subtotal = $money_format_subtotal; } private function salesTax($subtotal, $discount_amount =""){ $sales_tax = (STORE_SALES_TAX)?(float)STORE_SALES_TAX:8.875; $sales_tax =(($this->subtotal)*$sales_tax)/100; $sales_tax = round($sales_tax,2); $this->sales_tax = $sales_tax; } public function Tip() { //global $post_values; //$last_tip_selected = $post_values->tip > 0 ? $post_values->tip : "" ; $tip_output = "<select id='tip' name='tip'>"; for($tip=0.00; $tip<=11.75; $tip+=0.25){ if( $tip == "2") {$selected = " selected";} else {$selected ="";} $formatted_tip = money_format('%i',$tip); $tip_output .= "<option {$selected} id='selected_tip' value='$formatted_tip'>"."$".$formatted_tip ."</option>".PHP_EOL; } $tip_output .= "</select>"; return $tip_output; } private function grandTotal(){ $grand_total = round($this->sales_tax+$this->subtotal+$this->tip,2); $grand_total_formatted = money_format('%i',$grand_total); $this->grand_total = $grand_total_formatted; } Hi guys, Was wondering if you could help. Apart from using a form are the other ways to POST to a mysql database? e.g. using clicking a link or so. I know this should be easy... I have several text input boxes where I enter data to be sent to one column of my database. Code: [Select] [while($row = mysql_fetch_array( $result )) { $i=1; if ($row['game_id']='$i') { echo "<tr>"; echo "<td>"; echo $row['date']; echo "</td><td>"; echo $row['team_name']; echo "</td><td>"; echo $row['owner']; echo "</td><td>"; echo "<input type='text' size='4' name='result[]'>"; echo "</td></tr>"; Not every box has a value so my array will end up with several numbers and several "blanks". I echoed the array using Code: [Select] $result = ("$_POST[result]"); and all the values are returned as expected. Now I need to UPDATE the "pt_spread" column in the database inserting all the values (even the blank values). I tried the following but can't get it to actually post anything into the database. Code: [Select] <?php header("Location: admin_main_entry.php"); include("opendatabase.php"); $result = ("$_POST[result]"); foreach ($result as $spread) { $sql = " UPDATE schedule SET pt_spread = '$spread' WHERE week_id = '$weekID'" ; mysql_query($sql); } mysql_close($con) ?>Can anyone show me the correct way to do this? Thanks. Code: [Select] <?php $con = mysql_connect("localhost", "root", ""); $name = $_GET['jente_navn']; $name = mysql_real_escape_string($name); $ip = $_SERVER['REMOTE_ADDR']; mysql_select_db("name", $con); if ( preg_match("/^[^a-z]|[^A-Z]+/i", $name) ) { die ("Feil: Kan bare bruke gyldige tegn"); }else{ $sql = 'SELECT * FROM banned WHERE name= \'' . $name . '\' OR ip= \'' . $ip . '\''; $result = mysql_query($sql); if( mysql_num_rows($result) ){ print "That Name, or your ip adress is. BANNED!"; } } $sql = "INSERT INTO girl ('girl','accepted','ip') VALUES ('$name', '0', '$ip');"; if ( mysql_query($sql, $con) ){ mysql_close($con); header('http://localhost/takk.php'); }else{ mysql_close($con); header('http://localhost/error.php'); } ?> I don't get any errors, but it still doesn't post the name in the database, even though the name doesn't exist or ain't banned. :s Hello, I made myself a simple blog system, but in my case "simple" becomes difficult when it comes to writing an article. Have you ever seen that movie about how facebook was created (I think it's called "Social network" or something like that)? As a newbie web developer I noticed how "Mark" was writting his blog post. I think it was an textarea, and when he was writing article, he wrote it with html tags, like <p>. So, I have now the same problem: when I'm writing article, I have to write it with all div's and p's and a's and img's and so on. I want to avoid that. Few ideas did pop to my head: use preg_replace for some elements, and set up some javascript WYSIWYG editor (but i really don't want it, and can't explain why, I just don't like it). I have a couple of css classes for images, both of them resizes images, one resizes it a lot, other not so much, both make them smaller. One class is for image to be on the left, so the text would wap that image from the right. After paragraph I must clear floats with css class. Other image class just takes full width available and if image is bigger that that available width - it resizes image. So no need to clear floats. How can I make my life easier when I'm writing article to my blog? Iv tried asking a lot of people and have had no luck resolving this issue, so I will try here. I have created a Form which gathers its information from a Database. The first form is a Dropdown Option, which when submitted takes you to another page. The new page is Supposed to use the value from the Dropdown to search the database and return the proper rows to populate a few text areas to edit the values. This is where I am stuck. Compared to what most of you create this is probably sloppy and not too well structured, but I am new to this. Anyways, I will provide more information below now. The following is the initial page with the first form. This is where you would select what page you wish to edit. (I believe this may be where the issue resides) - (I included the 'num' value before the 'name' value so that I could see it is getting the value from the database, which it is) <form method="post" action="pageedit.php"><br /> <?php include "config.php"; echo "<select name=\"page\">\n"; $conn = mysql_connect("localhost", "$username", "$password"); if (!$conn) { echo "Unable to connect to DB: " . mysql_error(); exit; } if (!mysql_select_db("$database")) { echo "Unable to select $database: " . mysql_error(); exit; } $sql = "SELECT * FROM sitePages"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "No rows found, nothing to print so am exiting"; exit; } while ($row = mysql_fetch_assoc($result)) { echo "<option value='"; echo $row['num']; echo "'>"; echo $row['num']; echo " - "; echo $row['name']; echo "</option>"; } echo "</select>"; ?> <br /> <input type="submit" /> </form> And then the following is the page that the form is sent to when submitted: (I have attempted to Echo the 'num' value sent so that I could verify that it is indeed sent, but it is not. I will post the message I receive after the PHP snippet <form method="post" action="pageeditinsert.php"><br /> <?php include "config.php"; echo $_POST['num']; $num=$_POST['num']; $conn = mysql_connect("localhost", "$username", "$password"); if (!$conn) { echo "Unable to connect to DB: " . mysql_error(); exit; } if (!mysql_select_db("$database")) { echo "Unable to select $database: " . mysql_error(); exit; } $sql = "SELECT * FROM sitepages WHERE num = '$num'"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "No rows found, nothing to print so am exiting"; exit; } while ($row = mysql_fetch_assoc($result)) { echo "<input name'num' type='hidden' class='form1' value='"; echo $num; echo "' maxlength='10' id='cat' /><br /><br /><br />"; echo "<input name='name' type='text' class='form1' value='"; echo $row['name']; echo "' maxlength='20' id='name' /><br /><br />"; echo "<input name='desc' type='text' class='form1' value='"; echo $row['desc']; echo "' maxlength='100' id='desc' /><br /><br /><br />"; echo "<input name='title' type='text' class='form1' value='"; echo $row['title']; echo "' maxlength='100' id='title' /><br /><br /><br />"; echo "<input name'cat' type='hidden' class='form1' value='cat' maxlength='3' id='cat' /><br /><br /><br />"; } ?> <br /><br /><br /> <center><input type="submit" /><input type="reset" /></center> </form> Below is the message I receive when attempting to echo the POSTed 'num' value: Quote Notice: Undefined index: num in C:\wamp\www\gondieCOM\editor\edit\pageedit.php on line 16 Call Stack # Time Memory Function Location 1 0.0025 687600 {main}( ) ..\pageedit.php:0 (I am running the latest WAMP release on my personal PC for testing purposes until I have finished this and upload it to my hosting server) Anyways thanks for your time. Hopefully someone has an idea for me. Hi,
Webapp noob here.
I have an application that is going to be data-heavy, so I would like to avoid saving things to the database whenever possible. The application in a nutshell is an android application wired up to a php web app(with MySQL) where you can send requests to the phone and the phone will respond with text or image data with POST.
The normal way to do this would be for the phone to post the data to the database, then have the webapp display it. However, what im wondering is if it is possible for a user on the webapp to request information from the phone, and then when the phone replies using a POST to display the information temporarily in maybe a popup window instead of having to save it to the database.
Thanks!
Hi, i'm currently building essentially an API for my URL shortener site so other sites can implement it. But i've hit a stumbling block on the last script of the lot(the others merely collate the data and store it) In this last script, i need to find all this data, stored in cookies and inout it into the database, as the main site does(i'm confident this bit works, as it's the code from the main site just copied across, and i can see the data in the database). Importantly, i then need o look in another table for the callback URL to send the data back to $urltoshorten = $_COOKIE["URLtoShorten"]; $alias = $_COOKIE["urlalias"]; $key = $_COOKIE["key"]; //connection details go in here $alias =mysql_real_escape_string($alias); $urltoshorten = mysql_real_escape_string($urltoshorten); $base = "http://s-url.co.uk/i/?id="; $url = $base . $alias ; //this is the main bit, where the URL shortening occurs mysql_query("INSERT INTO table (id, name) VALUES('$alias', '$urltoshorten')")or die( mysql_error()); //this is where the callback url is looked for $result= mysql_query("SELECT apiaddress FROM apistuff WHERE apinumber='$key'")or die( mysql_error()); $row = mysql_fetch_array($result); $new = $row[apiaddress]; //I then start a CURL session to POST data to the page in question, as found above $Curl_Session = curl_init($new); curl_setopt ($Curl_Session, CURLOPT_POST, 1); curl_setopt ($Curl_Session, CURLOPT_POSTFIELDS, "shortenedurl=$url"); curl_exec ($Curl_Session); curl_close ($Curl_Session); annoyingly, no errors get thrown, as far as i can see, i just end at a blank page without being returned to the callback page. I'm rather stumped on this one, where am i likely to be going wrong/how do i go about correcting it. Cheers Joe This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=347360.0 Hi all, Thanks for reading. I'm hella frustrated at this script I wrote: for some reason, it will not work correctly. Basically, it works. The first 4 names in the table on the database show up when searched. But, anything past these four names in the database will not show up as a result when searched! I'm pulling my hair out here! It's really simple - take a gander: Code: [Select] if (isset($_POST['submit'])) { $search = $_POST['search']; $searchQuery = mysql_query("SELECT * FROM Accounts WHERE FullName='$search'"); if (mysql_num_rows($searchQuery) == 0) { $result = "Your search returned no results. Please try again."; } else { $results = 1; while ($getSearchResults = mysql_fetch_array($searchQuery)) { $fullName = $getSearchResults['FullName']; $result = "Name: ".$fullName.""; } } } ?> ...and the HTML form... Code: [Select] <form action="search.php" method="post"> <p>Search: <input type="text" name="search" size="35" maxlength="100" /></p> <p><input type="submit" value="Search" name="submit" /></p> <?php echo $result; ?> </form> Does anyone have any ideas? after cloasing connection of database i still got the values form database. Code: [Select] <?php session_start(); /* * To change this template, choose Tools | Templates * and open the template in the editor. */ require_once '../database/db_connecting.php'; $dbname="sahansevena";//set database name $con= setConnections();//make connections use implemented methode in db_connectiong.php mysql_select_db($dbname, $con); //update the time and date of the admin table $update_time="update admin set last_logged_date =CURDATE(), last_log_time=CURTIME() where username='$uname'limit 3,4"; //my admin table contain 5 colums they are id, username,password, last_logged_date, last_log_time $link= mysql_query($update_time); // mysql_select_db($dbname, $link); //$con=mysql_connect('localhost', 'root','ijts'); $result="select * from admin where username='a'"; $result=mysql_query($result); mysql_close($con); //here i just check after closing data baseconnection whether i do get reselts but i do, why? echo "after the cnnection was closed"; if(!$result){ echo "cont fetch data"; }else{ $row= mysql_fetch_array($result); echo "id".$row[0]."usrname".$row[1]."passwped".$row[2]."date".$row[3]."time".$row[4]; } // echo "<html>"; //echo "<table border='1' cellspacing='1' cellpadding='2' align='center'>"; // echo "<thead>"; // echo"<tr>"; // echo "<th>"; // echo ID; // echo"</th>"; // echo" <th>";echo Username; echo"</th>"; // echo"<th>";echo Password; echo"</th>"; // echo"<th>";echo Last_logged_date; echo "</th>"; // echo "<th>";echo Last_logged_time; echo "</th>"; // echo" </tr>"; // echo" </thead>"; // echo" <tbody>"; //while($row= mysql_fetch_array($result,MYSQL_BOTH)){ // echo "<tr>"; // echo "<td>"; // echo $row[0]; // echo "</td>"; // echo "<td>"; // echo $row[1]; // echo "</td>"; // echo "<td>"; // echo $row[2]; // echo "</td>"; // echo "<td>"; // echo $row[3]; // echo "</td>"; // echo "<td>"; // echo $row[4]; // echo "</td>"; // echo "</tr>"; // } // echo" </tbody>"; // echo "</table>"; // echo "</html>"; session_destroy(); session_commit(); echo "session and database are closed but i still get values from doatabase session is destroyed".$_SESSION['admin']; ?> session is destroyed but database connection is not closed. thanks Hello. I am trying to pass along a variable in an email auto response ($park), however if the variable is 2 words then it only passes along the first word. Any info would be great. Code: [Select] <?php $to = "$email"; $subject = "Event Signup Confirmation"; $message = "Hello $firstname! Thank you for signing up to work the $park event. Someone will contact you shortly. Event Information Park: $park Date: $orderdate Time: $hour:$min $ampm Description: $description Crew Leader: $leader"; $from = "guy@xxxx.com"; $headers = "From: $from"; mail($to,$subject,$message,$headers); echo "Thank you for signing up. You will receive an email shortly letting you know event details and who your crew leader is."; ?> Here is where I'm starting: Code: [Select] SELECT * FROM wp_usermeta WHERE meta_key = 'wp_1_s2member_custom_fields' AND meta_value LIKE '%3%' As the PHP produces the page, I'm going to have 15 different options coming from the Code: [Select] meta_value LIKE part. I'm assuming I can set up my 15 different DIVs, each with their own IF statement involving the meta_value. Right? I'm not going to have to have 15 different queries, am I? I assume it would start like this: Code: [Select] $query = 'SELECT * FROM wp_usermeta WHERE meta_key = "wp_1_s2member_custom_fields"'; $results = mysql_query($query); while($line = mysql_fetch_assoc($results)) But from there, I don't know if it's possible to deal with partial data with IF statements. Is there a way to look for a File without needing the Extension?? If I have the File... Code: [Select] someUserPicture.jpg ...and I have the string "someUserPicture", is there a way to use file_exists() and get it to work properly? Thanks, Debbie Hi guys, I have this code below that selects and display all events from my database table. E.g if an event titled 'PHP' starts 5th March and ends 6th March (03/05/2012 - 03/06/2012) Code: [Select] //SQL QUERY for Event $sqlCount = mysql_query("select * from eventcalender"); $noOfEvent = 0; while($Event = mysql_fetch_array($sqlCount)){ $startDate = $Event['startDate']; $endDate = $Event['endDate']; //split date list($smonth, $sday, $syear) = explode('/',$Event['startDate']); list($emonth, $eday, $eyear) = explode('/',$Event['endDate']); //change date to date time format $start = new DateTime($sday.'-'.$smonth.'-'.$syear); // DD-MM-YYYY $endDate= new DateTime($eday.'-'.$emonth.'-'.$eyear); // DD-MM-YYYY $curdate = new DateTime($i.'-'.$month.'-'.$year); if ($start <= $curdate && $curdate <= $endDate) { $noOfEvent++; $eventTitleList = $eventTitleList."<br />".$Event['Title']; } } My question is if I had a drop down and the user selects a half day or partial day for the end date (03/06/2012) how do I get the calender to display the word (Half day) on the end date without displaying it on the start date so as to indicate on the calender that the end date is a half day. I would appreciate you help and advice. Thanks $color=array("01 orange","02 blue","03 red"); If my array was structured this way where the first two characters represented a code, how would I be able to display the code and color distinctly? Hi, I want to show part of the text from a page containing my article on my main page. The article resides in a database in mysql. How do I limit the amount of text that is shown without setting up a separate excerpt box for the article. I want to then provide a link so the user can go to another page that displays the entire article. Thanks for any suggestions. I've run into a little bit of a logistical nightmare on some registration pages I've taken over work on. On these pages, parents register their kids for classes. The pages have been coded as such: page one: the user enters name and personal info, and selects one or two classes to register for, on submit, they go to page two. page two: their info is entered into the mysql database's registration table on a unique id The user verifies the total, enters a discount and submits page three: credit card info is added to registration table, and sent to authorize.net. page four: payment processed, and they enter the data for their kids into the attendees table page five: confirmation and done. My issue is that, at first I saw people entering page one data, going to page two, then for some reason, hitting the back button. They could then enter the data again. I'd have two entries in the registration table for the same person. I was going to put some sort of unique key on the name and an email, but then I saw scenario two... Another person enters data and registers one kid.. then for whatever personal reason goes back and registers a second kid in a completely separate transaction. So I can't put that key on there, but is there a way to prevent them from going back and reentering twice. I don't want to have to blow up the code to do it at the end of everything. and that would take implementing sessions, wouldn't it? I'm not so versed at that. Any thoughts? I have a array of file path strings and trying to search the array for a string that would be the end of the path sting and return the index of the file path that contains the string. I've tried using something like this, but it finds the keyword in anyplace in the file path. I've also tried strripos() as well with the same results. Any suggestions? function array_search_partial($arr, $keyword) { foreach ($arr as $index => $string) { if(strpos($string, $keyword) !== FALSE) { return $index; } } }
|