PHP - Php Mysql Help With Currency Convert
Hi,
i have 2 currencies in my mysql and when user add new article, he choose currency and price. Now i need search engine for searching articles, and i have problem in part when user choose to show only articles between 100 and 200 euros, so i need help to convert all currencies to euro(all in mysql query) and show from 100 to 200 dollars, so if article price is 100 euros, then to show it too. Can someone help me ? 1 euro = 0.70 $ (example for values) Similar Tutorialscreate table mimi (mimiId int(11) not null, mimiBody varchar(255) ); <?php //connecting to database include_once ('conn.php'); $sql ="SELECT mimiId, mimiBody FROM mimi"; $result = mysqli_query($conn, $sql ); $mimi = mysqli_fetch_assoc($result); $mimiId ='<span>No: '.$mimi['mimiId'].'</span>'; $mimiBody ='<p class="leading text-justify">'.$mimi['mimiBody'].'</p>'; ?> //what is next? i want to download pdf or text document after clicking button or link how to do that Hi, I am trying to convert the register & login script from mysql to mysqli. I have converted the easy parts and have the connection to the database, but the following functions all need changing and I can't work out the correct solution mainly due to the deprecation of mysql_result() The code that needs updating is <?php function user_count() { return mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `active` = 1"), 0); } function users_online() { return mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `logged_in` = 1"), 0); } function change_profile_image($user_id, $file_temp, $file_extn) { $file_path = 'images/profile/' . substr(md5(time()), 0, 10) . '.' . $file_extn; move_uploaded_file($file_temp, $file_path); mysql_query("UPDATE `users` SET `profile` = '" . mysql_real_escape_string($file_path) . "' WHERE `user_id` = " . (int)$user_id); } function has_access($user_id, $type) { $user_id = (int)$user_id; $type = (int)$type; return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_id` = $user_id AND `type` = $type"), 0) == 1) ? true : false; } function activate($email, $email_code) { $email = mysql_real_escape_string($email); $email_code = mysql_real_escape_string($email_code); if (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `active` = 0"), 0) == 1) { mysql_query("UPDATE `users` SET `active` = 1 WHERE `email` = '$email'"); return true; } else { return false; } } function user_exists($username) { $username = sanitize($username); $query = mysql_query("SELECT COUNT('user_id') FROM `users` WHERE `username` = '$username'"); return (mysql_result($query, 0) == 1) ? true : false; } function email_exists($email) { $email = sanitize($email); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'"), 0) == 1) ? true : false; } function user_id_from_username($username) { $username = sanitize($username); return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id'); } function user_id_from_email($email) { $email = sanitize($email); return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `email` = '$email'"), 0, 'user_id'); } function login($username, $password) { $user_id = user_id_from_username($username); mysql_query("UPDATE `users` SET `logged_in` = 1 WHERE `user_id` = $user_id"); $username = sanitize($username); $password = md5($password); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0) == 1) ? $user_id : false; } ?>And here is what the converter gave me: function user_count() { return mysql_result(mysqli_query($GLOBALS["___mysqli_ston"], "SELECT COUNT(`user_id`) FROM `users` WHERE `active` = 1"), 0); } function users_online() { return mysql_result(mysqli_query($GLOBALS["___mysqli_ston"], "SELECT COUNT(`user_id`) FROM `users` WHERE `logged_in` = 1"), 0); } function change_profile_image($user_id, $file_temp, $file_extn) { $file_path = 'images/profile/' . substr(md5(time()), 0, 10) . '.' . $file_extn; move_uploaded_file($file_temp, $file_path); mysql_query("UPDATE `users` SET `profile` = '" . mysql_real_escape_string($file_path) . "' WHERE `user_id` = " . (int)$user_id); } function has_access($user_id, $type) { $user_id = (int)$user_id; $type = (int)$type; return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_id` = $user_id AND `type` = $type"), 0) == 1) ? true : false; } function activate($email, $email_code) { $email = mysql_real_escape_string($email); $email_code = mysql_real_escape_string($email_code); if (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `active` = 0"), 0) == 1) { mysql_query("UPDATE `users` SET `active` = 1 WHERE `email` = '$email'"); return true; } else { return false; } } function user_exists($username) { $username = sanitize($username); $query = mysql_query("SELECT COUNT('user_id') FROM `users` WHERE `username` = '$username'"); return (mysql_result($query, 0) == 1) ? true : false; } function email_exists($email) { $email = sanitize($email); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'"), 0) == 1) ? true : false; } function user_id_from_username($username) { $username = sanitize($username); return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id'); } function user_id_from_email($email) { $email = sanitize($email); return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `email` = '$email'"), 0, 'user_id'); } function login($username, $password) { $user_id = user_id_from_username($username); mysql_query("UPDATE `users` SET `logged_in` = 1 WHERE `user_id` = $user_id"); $username = sanitize($username); $password = md5($password); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0) == 1) ? $user_id : false; } ?>Please could someone point me in the right direction here? Also my site works perfectly well with MySQL, do I have to convert it to MySQLi? Many Thanks Paul If anyone knows how to solve this, it would be much appreciated. I already have a website template and would prefer to continue with mysqli instead of PDO. Many Thanks Paul Hi Everyone, I'm trying to convert my MySql data into variables so I can use them on my website. For example, if I want to convert a city or even first or last name into a variable. How would I go about doing that? Thanks everyone! Hello guys, I have purchased a new book for PHP called Professional PHP 6. But the bad news is that the whole book was written for PostgreSQL NOT for MYSQL which I'm familiar with! I have this code, I have tried to do so many things to get it working! but nothing seems to have it working! Long story short, I have failed to convert the code to work with MySQL! Here is my code, in case some one will offer a help, or a reference to go to if some similar case comes up on my way. <?php class Widget { private $id; private $name; private $description; private $hDB; private $needsUpdating = false; public function __construct($widgetID) { //The widgetID parameter is the primary key of a //record in the database containing the information //for this object //Create a connection handle and store it in a private member variable //This code assumes the DB is called "parts" $this->hDB = pg_connect('dbname=parts user=postgres'); if(! is_resource($this->hDB)) { throw new Exception("Unable to connect to the database."); } $sql = "SELECT name, description FROM widget WHERE widgetid = $widgetID"; $rs = pg_query($this->hDB, $sql); if(! is_resource($rs)) { throw new Exception("An error occurred selecting from the database."); } if(! pg_num_rows($rs)) { throw new Exception("The specified widget does not exist!"); } $data = pg_fetch_array($rs); $this->id = $widgetID; } public function getName() { return $this->name; } public function getDescription() { return $this->description; } public function setName($name) { $this->name = $name; $this->needsUpdating = true; } public function setDescription($description) { $this->description = $description; $this->needsUpdating = true; } public function __destruct() { if($this->needsUpdating) { $sql = "UPDATE widget SET "; $sql .= "name = " . pg_escape_string($this->name) . ", "; $sql .= "description = " . pg_escape_string($this->description) . ""; $sql .= "WHERE widgetID = " . $this->id; $rs = pg_query($this->hDB, $sql); } pg_close($this->hDB); } } ?> FYI: I have tried mysql_pconnect ! results => failure! I have tried replacing the prefix "pg" to "mysql" or "mysqli"! results => failure! I have tried switching parameters, say in pg_query($resource, $query) TO mysql_query($query, $resource) results => failure too! Thank you in advance! I've been playing around with this code from http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart Objective: I'm trying to make the scripts work but without pulling the data from MySQL Database. Instead, I created an array and inserted some info there and trying to replicate the same results but getting confused. For example, on the Index.php file, I made the following changes: <?php // Start the session session_start(); // Include functions require_once('inc/functions.inc.php'); // Products multidimensional Array $products = array("book" => array( 'id' => '1', 'title' => 'Learn Your ABC\'s', 'author' => 'John Doe', 'price' => '14.95'), "video" => array('id' => '2', 'title' => 'Visual Guide to learn', 'author' => 'Adam Smith', 'price' => '21.38'), "puzzle" => array('id' => '3', 'title' => 'Can You Solve?', 'author' => 'Sara Brown', 'price' => '9.41'), "exam" => array('id' => '4', 'title' => 'Test Your Knowledge', 'author' => 'Kim Carver', 'price' => '11.15')); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo &#0183; Bookshop</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Books In Our Store</h1> <?php /* $sql = 'SELECT * FROM books ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': $'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); */ ?> <?php $output[] = '<ul>'; foreach ($products as $product => $product_item) { // $flavor is the key and $piece is the value foreach ($product_item as $item => $piece) { if ($item == "id") { # Conditional logic defined to map specific keys to specified name value $row['id'] = $piece; // echo "The id is ". $id."<br />"; // set just to confirm value correct for variable } elseif ($item == "title") { # Conditional logic defined to map 1st key to price value $row['title'] = $piece; // echo "The title is ". $title."<br />"; // set just to confirm value correct for variable } elseif ($item == "author") { # Conditional logic defined to map 1st key to price value $row['author'] = $piece; // echo "The author is ". $author."<br />"; // set just to confirm value correct for variable } elseif ($item == "price") { # Conditional logic defined to map 1st key to shipping value $row['price'] = $piece; // echo "Price: ". $price."<br /><br />"; // set just to confirm value correct for variable } $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': $'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; $output[] = '</ul>'; echo join('',$output); } } ?> </div> </body> </html> And here's the original index.php before my edits which show the sql query to the db: <?php // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Start the session session_start(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo &#0183; Bookshop</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Books In Our Store</h1> <?php $sql = 'SELECT * FROM books ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': £'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); ?> </div> </body> </html> Also, I included the zipped file of the entire script setup. Again, I'm trying to figure out how to make the cart work with using an array for the product instead of MySQL database. My goal is to remove ALL SQL statements from the scripts but stuck with the looping portion to display the title, author, and price from the array as shown above. I have tried a large number of "solutions" to this but everytime I use them I see 0000-00-00 in my date field instead of the date even though I echoed and can see that the date looks correct. Here's where I'm at: I have a drop down for the month (1-12) and date fields (1-31) as well as a text input field for the year. Using the POST array, I have combined them into the xxxx-xx-xx format that I am using in my field as a date field in mysql. <code> $date_value =$_POST['year'].'-'.$_POST['month'].'-'.$_POST['day']; echo $date_value; </code> This outputs 2012-5-7 in my test echo but 0000-00-00 in the database. I have tried unsuccessfully to use in a numberof suggested versions of: strtotime() mktime Any help would be extremely appreciated. I am aware that I need to validate this data and insure that it is a valid date. That I'm okay with. I would like some help on getting it into the database. Hi I need to change a uk date dd/mm/yyyy to mysql format yyyy/mm/dd I have a user form where they enter the date in dd/mm/yyyy string format, i want to take that string, and convert it to mysql format yyyy/mm/dd Possible? Ive searched for ages and havent found a solution that works. Is there an easy solution to this? surely there must be Cheers Hi all, Can anyone please help me with my problem. I want to know how to round a decimal - eg. 12.34 to the nearest .10 so it would be 12.30 or if 12.35 go to 12.30 or 12.40. // my example: round(12.34, 2); // I want to to go to: 12.30 Any help is greatly appreciated. hi, how can i make a autoupdate currency table currency value CHF USD EURO KD (Kuwaiti Dinars) 1 Converted Value Converted Value Converted Value when the page loads, it will convert the currency and the value of CHF, USD and EURO are real time please kindly help tia Is there an easy way for me to return 123.50 instead of 123.5.... I'm trying to return the trailing zero? hi, how can i make a autoupdate currency table currency value CHF USD EURO KD (Kuwaiti Dinars) 1 Converted Value Converted Value Converted Value when the page loads, it will convert the currency and the value of CHF, USD and EURO are real time please kindly help tia hello everyone i am newbie to php just wanted to make a script for currency converter the problem i am facing is if i want to convert a value from $usd to $euro,$pond,$yen there are three possible values for usd kindly help me out with designing the values for tables and fetching data from them what will be structure of the table what will be the values kindly help me out it,s request thanks I'm trying to develop a function to check to see if the value inputted was in a currency format. I'm checking for: if the value is numeric if the value is an integer if not integer check the number of digits to the right of the decimal point I can't tell how the php function is_int() works though. I want to accept integers and also numbers with two decimal places. So accepted values will be "123" and also "123.99". The script tells me the value is not an integer no matter what. Code: [Select] <?php $num = $_POST['number']; $positionOfDecimalPoint = strpos($num, '.'); $numbersToLeft = substr($num,0,$positionOfDecimalPoint); $numbersToRight = substr($num,$positionOfDecimalPoint + 1);//Add one so decimal point isn't included in output. echo "You submitted ".$num."<br><br>"; if(!is_numeric($num)) { echo "Not Numeric"; } else { if(!is_int($num)) { $adecimal = strlen($numbersToRight); if($adecimal !== 2) { echo "There needs to be exactly two numbers after the decimal."; } echo "<br><br>The number is not an integer."; }else { echo "The integer is ".$num; } } ?> Hey there, I'm looking for some publicly available API that I can convert GPB to Dollars, that is updated often, can somebody show me how I could obtain such a API?. Thanks, Christopher. Unfortunately, I have got nearly zero knowledge in PHP. I'm just trying to add a drop-down menu on my website which will turn the prices in USD to other currencies. I'm trying hard to learn but it's too difficult for me at the moment. Here are codes written by someone else which I want to modify and apply to my website. I've tried the second PHP on my WAMP local server but it returns nothing. Both files were in the same folder. I don't know if these codes are correct. I'd appreciate if someone could tell me if the codes are wrong or they just don't work on WAMP server. Sorry the codes are quite long. Thanks in advance. Code: [Select] <?php /* File: currencyexchange.php Author: Gary White Last modified: July 6, 2005 Copyright (C) 2005, Gary White This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the included GNU General Public License for more details. If you received this file without the gpl.txt file, you may view it at: http://www.gnu.org/copyleft/gpl.html See the readme.txt file for usage. July 6, 2005 added the RON, Romania New Leu, to the currency list. */ // this simply gets an array of possible currency countries and names $allCurrencies=getCurrencyNames(); class currencyExchange{ ///////////////////////////////////////////////////////////////////////////////////////// // Public Properties // Note that these properties are public, but the values are all generated internally. // You should consider them read only during normal usage. // The only one you may want to access would be the $localFile property, if you wanted // to change the name of the local file used to cache a copy of the data. ///////////////////////////////////////////////////////////////////////////////////////// // $Supplier property will be the European Central Bank, assuming we get the data var $Supplier=""; // $Date property is the date of the exchange rate publication var $Date=""; // $Rates property is an associative array of rateobj objects with the three letter identifier as the array keys var $Rates=array(); // $Source property will be either "Local" or "Remote" depending on where the data comes from var $Source=""; // $Error property will contain any error messages generates along the way var $Error=""; // $localFile property is the file name used to cache a local copy of the XML file var $localFile="currencies_local.xml"; // $url property is the URL of the XML file at the European Central Bank var $url="http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"; ///////////////////////////////////////////////////////////////////////////////////////// // Public Methods ///////////////////////////////////////////////////////////////////////////////////////// function getData(){ $olderr=error_reporting(0); $this->Source="Local"; if(file_exists($this->localFile)){ // load it $this->xml=@file_get_contents($this->localFile); $this->parse(); // check if it's a weekend // what day of the week is it? $weekday=date("w"); // if it's a Sunday or Saturday if($weekday==0 || $weekday==6){ // go back to last Friday $date=date("Y-m-d",strtotime("last Friday")); } else { $date=date("Y-m-d"); } // if the date in the local file is not the same // as our current date, or last Friday for weekends if($this->Date!=$date){ // clear the data $this->clearData(); // get the remote file $this->xml=$this->getRemoteFile($this->url); if($this->parse()){ $this->Source="Remote"; // write the remote file data to a local copy of the file $this->saveLocalCopy(); } } // if we have a local copy }else{ $this->xml=$this->getRemoteFile($this->url); if($this->xml) // write the remote file data to a local copy of the file $this->saveLocalCopy(); } if(!$this->xml) $this->error="Failed to get data"; else{ $this->parse(); } // sort our rates on the keys ksort($this->Rates); error_reporting($olderr); return count($this->Rates); } function getRemoteFile($url){ $curl_handle = curl_init(); // Where should we get the data? curl_setopt ($curl_handle, CURLOPT_URL, $url); // This says not to dump it directly to the output stream, but instead // have it return as a string. curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1); // the following is optional, but you should consider setting it // anyway. It prevents your page from hanging if the remote site is // down. curl_setopt ($curl_handle, CURLOPT_CONNECTTIMEOUT, 1); // Now, YOU make the call. $buffer = curl_exec($curl_handle); // And tell it to shut down (when your done. You can always make more // calls if you want.) curl_close($curl_handle); // This is where i�d probably do some extra checks on what i just got. // Paranoia pays dividends. return $buffer; } function Convert($from, $to, $amount=1){ // Converts from one currency to another. The method expects at least two // parameters. The first param , $from, it the three letter identifier for // the currency you are converting from. The second param, $to, is the // three letter identifier for the currency you are converting to. The final // param, $amount, is the amount of the $from currency to convert. If omitted // the amount defaults to 1 and the function will return the amount of $to // currency that corresponds with 1 unit of the $from currency. if(array_key_exists($from, $this->Rates) && array_key_exists($to, $this->Rates)){ return ($amount * (($this->Rates[$to]->rate)/($this->Rates[$from]->rate))); }else{ $this->Error->Error = ""; if (!array_key_exists($from, $this->Rates)) $this->Error.="$from is not a recognized currency identifier "; if (!array_key_exists($from, $this->Rates)) $this->Error.="$to is not a recognized currency identifier"; return false; } } function setBaseCurrency($currency){ // This function converts all currencies to be based on one unit of // $base currency. It's only really useful if you want to output a // table of conversion factors. // get a factor to do our conversion based on our base currency $factor=$this->Rates[$currency]->rate; // modify the rates based on the base currency foreach(array_keys($this->Rates) as $k){ $rate=$this->Rates[$k]->rate / $factor; $this->Rates[$k]->rate=$rate; } return (count($this->Rates)>0); } ///////////////////////////////////////////////////////////////////////////////////////// // Private Methods // You should not need to call any of the following methods. ///////////////////////////////////////////////////////////////////////////////////////// function clearData(){ $this->Supplier=""; $this->Date=""; $this->Rates=array(); $this->Source=""; $this->xml=""; } function saveLocalCopy(){ $fp=fopen($_SERVER['DOCUMENT_ROOT'].$this->localFile,"w") or die("failed to write file"); fwrite($fp,$this->xml); fclose($fp); $this->parse(); $this->Source="Remote"; } function parse(){ if($this->xml){ $this->parser = xml_parser_create(); @xml_set_object($this->parser, $this); @xml_set_element_handler($this->parser, "startElement", "endElement"); @xml_set_character_data_handler($this->parser, "characterData"); $this->Rates['EUR']=new rateobj(); $this->Rates['EUR']->rate=1.00; $this->Rates['EUR']->currency="Euro"; xml_parse($this->parser, $this->xml, true) or die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); xml_parser_free($this->parser); } } function currencyExchange(){ $dir=pathinfo($_SERVER['PHP_SELF']); $dir=$dir['dirname']; $this->localFile="$dir/$this->localFile"; } function startElement($parser, $name, $attrs) { global $allCurrencies; $this->temp=""; $gwCurrencyExch=&$GLOBALS['gwCurrencyExch']; if($name=="CUBE"){ if(array_key_exists("TIME",$attrs)){ $this->Date=$attrs["TIME"]; } if(array_key_exists("CURRENCY",$attrs)){ $this->Rates[$attrs["CURRENCY"]]=new rateobj(); $this->Rates[$attrs["CURRENCY"]]->rate=$attrs["RATE"]; $this->Rates[$attrs["CURRENCY"]]->currency=$allCurrencies[$attrs["CURRENCY"]]; } } } function characterData($parser, $data){ $this->temp.=$data; } function endElement($parser, $name) { switch($name){ case "GESMES:NAME": $this->Supplier=$this->temp; break; case "GESMES:SUBJECT": $this->Report=$this->temp; break; } $temp=""; } } // end of ratelist class class gwSocket{ var $ClassName="gwSocket"; var $Version="0.6"; var $error=""; var $headers; var $maxRedirects=3; var $page=""; var $result=""; var $redirects=0; var $userAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"; function getUrl( $url ) { $retVal=""; $url_parsed = parse_url($url); $scheme = $url_parsed["scheme"]; $host = $url_parsed["host"]; $port = $url_parsed["port"]?$url_parsed["port"]:"80"; $user = $url_parsed["user"]; $pass = $url_parsed["pass"]; $path = $url_parsed["path"]?$url_parsed["path"]:"/"; $query = $url_parsed["query"]; $anchor = $url_parsed["fragment"]; if (!empty($host)){ // attempt to open the socket if($fp = fsockopen($host, $port, $errno, $errstr, 2)){ $path .= $query?"?$query":""; $path .= $anchor?"$anchor":""; // this is the request we send to the host $out = "GET $path ". "HTTP/1.0\r\n". "Host: $host\r\n". "Connection: Close\r\n". "User-Agent: $this->userAgent\r\n"; if($user) $out .= "Authorization: Basic ". base64_encode("$user:$pass")."\r\n"; $out .= "\r\n"; fputs($fp, $out); while (!feof($fp)) { $retVal.=fgets($fp, 128); } fclose($fp); } else { $this->error=$errstr; } $this->result=$retVal; $this->headers=$this->parseHeaders(trim(substr($retVal,0,strpos($retVal,"\r\n\r\n")))); $this->page=trim(stristr($retVal,"\r\n\r\n"))."\n"; if(isset($this->headers['Location'])){ $this->redirects++; if($this->redirects<$this->maxRedirects){ $location=$this->headers['Location']; $this->headers=array(); $this->result=""; $this->page=""; $this->getUrl($location); } } } return (!$retVal=""); } function parseHeaders($s){ $h=preg_split("/[\r\n]/",$s); foreach($h as $i){ $i=trim($i); if(strstr($i,":")){ list($k,$v)=explode(":",$i); $hdr[$k]=substr(stristr($i,":"),2); }else{ if(strlen($i)>3) $hdr[]=$i; } } if(isset($hdr[0])){ $hdr['Status']=$hdr[0]; unset($hdr[0]); } return $hdr; } } // end of gwSocket class class rateobj{ var $currency=""; var $rate=0; } function getCurrencyNames(){ $retVal['AED']="United Arab Emirates Dirham"; $retVal['AFA']="Afghanistan Afghani"; $retVal['ALL']="Albania Leke"; $retVal['ARS']="Argentina Peso"; $retVal['ATS']="Austria Schilling*"; $retVal['AUD']="Australia Dollar"; $retVal['BBD']="Barbados Dollar"; $retVal['BDT']="Bangladesh Taka"; $retVal['BEF']="Belgium Franc*"; $retVal['BGN']="Bulgaria Leva"; $retVal['BHD']="Bahrain Dinar"; $retVal['BMD']="Bermuda Dollar"; $retVal['BRL']="Brazil Reai"; $retVal['BSD']="Bahamas Dollar"; $retVal['CAD']="Canada Dollar"; $retVal['CHF']="Switzerland Franc"; $retVal['CLP']="Chile Peso"; $retVal['CNY']="China Yuan Renminbi"; $retVal['COP']="Colombia Peso"; $retVal['CRC']="Costa Rica Colone"; $retVal['CYP']="Cyprus Pound"; $retVal['CZK']="Czech Republic Koruny"; $retVal['DEM']="Germany Deutsche Mark*"; $retVal['DKK']="Denmark Kroner"; $retVal['DOP']="Dominican Republic Peso"; $retVal['DZD']="Algeria Dinar"; $retVal['EEK']="Estonia Krooni"; $retVal['EGP']="Egypt Pound"; $retVal['ESP']="Spain Peseta*"; $retVal['EUR']="Euro"; $retVal['FIM']="Finland Markkaa*"; $retVal['FJD']="Fiji Dollar"; $retVal['FRF']="France Franc*"; $retVal['GBP']="United Kingdom Pound"; $retVal['GRD']="Greece Drachmae*"; $retVal['HKD']="Hong Kong Dollar"; $retVal['HRK']="Croatia Kuna"; $retVal['HUF']="Hungary Forint"; $retVal['IDR']="Indonesia Rupiahs"; $retVal['IEP']="Ireland Pounds*"; $retVal['ILS']="Israel New Shekel"; $retVal['INR']="India Rupee"; $retVal['IQD']="Iraq Dinar"; $retVal['IRR']="Iran Rial"; $retVal['ISK']="Iceland Kronur"; $retVal['ITL']="Italy Lire*"; $retVal['JMD']="Jamaica Dollar"; $retVal['JOD']="Jordan Dinar"; $retVal['JPY']="Japan Yen"; $retVal['KES']="Kenya Shilling"; $retVal['KRW']="South Korea Won"; $retVal['KWD']="Kuwait Dinar"; $retVal['LBP']="Lebanon Pound"; $retVal['LKR']="Sri Lanka Rupee"; $retVal['LTL']="Lithuanian Lita"; $retVal['LVL']="Latvian Lat"; $retVal['LUF']="Luxembourg Franc*"; $retVal['MAD']="Morocco Dirham"; $retVal['MTL']="Malta Liri"; $retVal['MUR']="Mauritius Rupee"; $retVal['MXN']="Mexico Peso"; $retVal['MYR']="Malaysia Ringgit"; $retVal['NLG']="Dutch (Netherlands) Guilder*"; $retVal['NOK']="Norway Kroner"; $retVal['NZD']="New Zealand Dollar"; $retVal['OMR']="Oman Rial"; $retVal['PEN']="Peru Nuevos Sole"; $retVal['PHP']="Philippines Peso"; $retVal['PKR']="Pakistan Rupee"; $retVal['PLN']="Poland Zlotych"; $retVal['PTE']="Portugal Escudo*"; $retVal['QAR']="Qatar Riyal"; $retVal['ROL']="Romania Lei"; $retVal['RON']="Romania New Leu"; $retVal['RUB']="Russia Ruble"; $retVal['SAR']="Saudi Arabia Riyal"; $retVal['SDD']="Sudan Dinar"; $retVal['SEK']="Sweden Kronor"; $retVal['SGD']="Singapore Dollar"; $retVal['SIT']="Slovenia Tolar"; $retVal['SKK']="Slovakia Koruny"; $retVal['THB']="Thailand Baht"; $retVal['TND']="Tunisia Dinar"; $retVal['TRL']="Turkey Lira*"; $retVal['TRY']="Turkey New Lira"; $retVal['TTD']="Trinidad and Tobago Dollar"; $retVal['TWD']="Taiwan New Dollar"; $retVal['USD']="United States Dollar"; $retVal['VEB']="Venezuela Bolivare"; $retVal['VND']="Vietnam Dong"; $retVal['XAF']="CFA BEAC Franc"; $retVal['XAG']="Silver Ounce"; $retVal['XAU']="Gold Ounce"; $retVal['XCD']="Eastern Caribbean Dollar"; $retVal['XDR']="IMF Special Drawing Right"; $retVal['XOF']="CFA BCEAO Franc"; $retVal['XPD']="Palladium Ounce"; $retVal['XPF']="CFP Franc"; $retVal['XPT']="Platinum Ounce"; $retVal['ZAR']="South Africa Rand"; $retVal['ZMK']="Zambia Kwacha"; return $retVal; } ?> Code: [Select] <?php /* This is a sample file that demonstrates the usage of the currencyExchange class. For purposes of this example, make certain that currencyexchange_class.php is saved in the same directory as this file. */ //error_reporting(0); $path=pathinfo($_SERVER['PHP_SELF']); $path=$_SERVER['DOCUMENT_ROOT'].$path['dirname']; require_once("$path/currencyexchange_class.php"); $cx=new currencyExchange(); $cx->getData(); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta http-equiv="imagetoolbar" content="no"> <meta name="mssmarttagspreventparsing" content="true"> <meta http-equiv="MSThemeCompatible" content="No"> <title>Currency Conversion Example</title> <style type="text/css"> body{ background-color: #eee; color: #333; font: small Verdana, Arial, Helvetica, sans-serif } #pricebox{ background-color: #f7f7f7; border:1px solid #000; margin: 50px auto; padding: 10px; width: 300px; } #pricebox h1, #pricebox h2, #pricebox p{ margin: 0; padding: 0; text-align: center; } h1{font-size: 160%;} h2{font-size: 140%;} </style> </head> <body> <div id="pricebox"> <h1>Get the New Widget</h1> <h2>Price $250.00 U.S. dollars</h2> <p><?php if ($euro=$cx->Convert("USD","EUR",250)){ $euro=number_format($euro,2); echo "€$euro Euros "; } if ($pound=$cx->Convert("USD","GBP",250)){ $pound=number_format($pound,2); echo "<br>\n£$pound British Pounds</p>\n" ."<p style=\"font-size:smaller;border-top: 1px solid #666;\">Non U.S. pricing based on exchange rates<br>\nin effect as of $cx->Date"; } ?></p></div> </body> </html> I am looking into sotring values in the sql database as "29824478.15" for example, now i use the number_format function to display as: 29,824,478 is it possible to get it to display as: 29.8m if its a million number and 0.29m if its less than a million for example? When I post the data to mysql I want to submit the value as an integer. How can I make this $12,000 be 12000? Does anyone know how I can validate US currency using php that is entered into a textbox? The textbox is setup as a decimal in mysql and i'm trying to make sure only decimals are entered so when php calculates the values entered I don't receive errors. Hi all, I am using some code i wrote for www.tingifts.com and although it works fine on that site, it has problems on http://www.regalosdehojalata.es/ The code relates to passing a currency symbol to a variable for inclusion on a page hosted by the payment gateway. Before I get into code, does anyone else have any experience with foreign languages interfering with php code, and if so, is there an easy way of getting around the issue? I have added slashes to all variables, so I wouldn't think that this would be the problem. Suggestions? Neil |