PHP - Is Converting Product Price To Cents The Best Way To Store Value In The Database?
Say I have two functions that convert from Dollar to Cents and Cents to Dollar. function convertToDollar($value) { $amount = $value / 100; return $amount; } function convertToCents($value) { $amount = $value * 100; return $amount; } Currently I convert all the Dollar amounts to cents and store the cents in the mysql database column. When I showcase those amounts on a page, I simply convert the Cents back to Dollar. Am I doing this correctly or is there a better way to store product pricing in mysql table? Similar TutorialsI am getting ready to code my e-commerce module, and could use some helping figuring out how to submit the product price. On the product details page, if I have a button called "Add to Cart", would I want to use a hidden HTML field to submit the "product_price"?
<?php
$id = $_GET['id']; $pdf = new FPDF('P','mm', array(80,200)); $pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Line(10,18,72,18);
$pdf->SetFont('Arial','',8);
$pdf->SetFont('Arial','',8);
$pdf->SetFont('Arial','',8);
$pdf->Line(10,30,72,30);
$pdf->SetY(31);
$pdf->SetFont('Courier','B',8);
$pdf->SetFont('Courier','BI',8);
$pdf->SetFont('Courier','B',8);
$pdf->SetFont('Courier','BI',8);
$pdf->SetFont('Courier','B',8);
$pdf->SetFont('Courier','BI',8);
$pdf->SetFont('Courier','BI',8);
$pdf->SetX(6);
$select = $pdo->prepare("SELECT * FROM tbl_invoice_detail WHERE invoice_id=$id");
//////////////////////////////////////////////
$pdf->SetFont('Arial','BI',7);
$pdf->SetX(43);
$pdf->SetFont('Arial','BI',7);
$pdf->SetX(43);
$pdf->SetFont('Arial','BI',7);
//////////////////////////////////////////////
$pdf->SetFont('Arial','BU',5); $pdf->Output(); Hi all,
How can i auto populate the price of an item based on a chosen product and then auto calculate the price and quantity before hitting the ADD button. The Unit price should be auto populated based on valu from the database. The amount is the Unit Price times the Quantity of the Product Selected. Thanks My form <form action="" method="post" data-toggle="validator"> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label>Item Name</label> <select id="username" name="item_name" class="form-control inputs" data-error="Select Item" required> <option value="">Chose Item</option> <?php $stmt = $pdo->query(" SELECT item_name FROM stocks ORDER BY item_name ASC "); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $item_name = $row['item_name']; echo "<option value=\"$item_name\"> $item_name </option>"; } ?> </select> <div class="help-block with-errors"></div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>Unit Price</label> <input type="number" class="form-control" name="item_price"> <div class="help-block with-errors"></div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>Item Quantity</label> <input type="number" class="form-control" name="item_qty" required data-error="Stock Quantity is missing"> <div class="help-block with-errors"></div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>Amount</label> <input type="number" class="form-control" name="amount" > <div class="help-block with-errors"></div> </div> </div> </div> <br> <span class="input-group-btn"> <input name="send" type="submit" class="btn btn-danger btn-form display-4 rounded" value="ADD"> </span> </form>Edited May 4, 2019 by I-AM-OBODO Hi there i have a big issues which is starting to cause me lots of stress. I have two tables one which is products and contains the following below and the other which is additionalCategories which the contains is also below. products id name image1 image2 image3 image4 image5 description department category subcategory Price additonalCategories id departmentID categoryID subcategoryID productID i have made a products upload script to my site where i can add products too it saves the category and subcategory id's in the fields above then if i wish to add the product to additional categories i do so and again this adds all the data to the addiotnalCategories table. however i can seems to be able to display this on the view products page i tried the below code but get no luck Code: [Select] <?php session_start(); $username=$_SESSION['username']; include_once"../includes/db_connect.php"; $cat=$_GET['cat']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <?php $query("SELECT products.name AS name, products.price AS price, addtionalCategories.productID AS productID FROM products, addtionalCategories WHERE category='$cat' AND products.id = addtionalCategories.productID"); while($fetch=mysql_fetch_object($query)){ echo"$fetch->name"; } ?> </body> </html> i need a way in which on the page it check the category id then finds all the products that are saved in the additionalCategories table then to find the data saved in the products table such as the name and price etc please any help will be appreciated thank you for reading Hello, I've created a page search to return results from my database inventory. On top of these results I would like to display a seperate list of five products not included in the search results but share the same sub_category_b (a column in my SQL table). Posted below is my primary query of the database. If anyone can help me out with this it would be appreciated. Code: [Select] $colname_product = "-1"; if (isset($_GET['title'])) { $colname_product = $_GET['title']; } mysql_select_db($database_inventory, $inventory); $query_product = sprintf("SELECT * FROM inventory WHERE item_name LIKE %s OR item_desc LIKE %s ", GetSQLValueString("%" . $colname_product . "%", "text"),GetSQLValueString("%" . $colname_product . "%", "text")); $product = mysql_query($query_product, $inventory) or die(mysql_error()); $row_product = mysql_fetch_assoc($product); I've fooled around with this one for some time and haven't come up with a clear cut answer. Thank you in advance! I have a list of products in database and some have the same itemid but a different price depending on size What i want to do i if the itemid has more than one size, take the smallest price and then add the word "From" at the beginning. I've tried using the MIN() function but can't get it to do what i want. If there is only one size it works fine but if there is more than one it just says "From 0.00" Code: [Select] while ($row = $result->fetch()) { if(!isset($items[$row['itemid']])) { $items[$row['itemid']] = $row; } $items[$row['itemid']]['sizes'][$row['size']] = $row['price']; ### CHANGED ### } foreach($items AS $subitem) { list($prodid, $itemid, $item, $size, $description, $shortdesc, $image, $price) = $subitem; //Create field for item name based upon record count if(count($subitem['sizes']) > 1) { /*$item_name_field = "<ul>\n"; foreach($subitem['sizes'] as $size => $price) ### CHANGED ### {*/ //} //$item_name_field .= "<ul>\n"; $myprice = explode(".",number_format(min($subitem['price']),2)); $item_name_field .= "<li>From ".$myprice[0].".".$myprice[1]." {$size}</li>\n"; } else { $myprice = explode(".",number_format($subitem['price'],2)); $item_name_field .= "<li><span class=\"ucprice\">£".$myprice[0]."<?span><span class=\"lcprice\">.".$myprice[1]."</span></li>\n"; } I've been doing some research and I was wondering what the best way is to store IP addresses in a MySQL database, and what would be the field type and length? I've seen that you can use the inet_aton() function but supposedly this doesn't support IPv4. So is there a workaround using these functions? Alternatively, if I was to just store the IP address as it is, what type of field and length would I be looking at? I've read somewhere that 45 is the max? Anyone could help or giude how to secure this script by storing session into database?
login.php
<?php //Start session session_start(); //Include database connection details require_once('config.php'); //Get ip function get_client_ip() { $ipaddress = ''; if ($_SERVER['HTTP_CLIENT_IP']) $ipaddress = $_SERVER['HTTP_CLIENT_IP']; else if($_SERVER['HTTP_X_FORWARDED_FOR']) $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; else if($_SERVER['HTTP_X_FORWARDED']) $ipaddress = $_SERVER['HTTP_X_FORWARDED']; else if($_SERVER['HTTP_FORWARDED_FOR']) $ipaddress = $_SERVER['HTTP_FORWARDED_FOR']; else if($_SERVER['HTTP_FORWARDED']) $ipaddress = $_SERVER['HTTP_FORWARDED']; else if($_SERVER['REMOTE_ADDR']) $ipaddress = $_SERVER['REMOTE_ADDR']; else $ipaddress = 'UNKNOWN'; return $ipaddress; } //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $login = clean($_POST['login']); $password = clean($_POST['password']); $ip = get_client_ip(); //Input Validations if($login == '') { $errmsg_arr[] = 'Login ID missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } /* if($login != '' || $password != '') { if($login !='admin' && $ip !=''.$log_ip.''){ $errmsg_arr[] = 'Your IP <b>'.$ip.'</b> is not recognized...'; $errflag = true; } } */ //If there are input validations, redirect back to the login form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); //header("location: index.php"); echo ('<meta http-equiv="refresh" content="0;url=index.php">'); exit(); } //Create query $qry="SELECT * FROM members WHERE login='$login' AND passwd='".$_POST['password']."'"; $result=mysql_query($qry); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) == 1) { //Login Successful session_regenerate_id(); $member = mysql_fetch_assoc($result); $_SESSION['SESS_MEMBER_ID'] = $member['member_id']; $_SESSION['SESS_LOGIN_NAME'] = $member['login']; $_SESSION['SESS_PASS'] = $member['passwd']; session_write_close(); //header("location: member-index.php"); echo ('<meta http-equiv="refresh" content="0;url=member-index.php">'); exit(); }else { //Login failed //header("location: login-failed.php"); echo ('<meta http-equiv="refresh" content="0;url=login-failed.php">'); exit(); } }else { die("Query failed"); } ?>auth.php (included on top of all php pages <?php //Start session session_start(); //Check whether the session variable SESS_MEMBER_ID is present or not if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) { //header("location: access-denied.php"); echo ('<meta http-equiv="refresh" content="0;url=access-denied.php">'); exit(); } ?> What is the better way, in terms of best practice and also speed of storing PHP objects in a database? Is it: Serialize Code: [Select] $SQL = "INSERT INTO my_table (my_object) VALUES ('" . seralize($php_object). "')"; OR JSON Code: [Select] $SQL = "INSERT INTO my_table (my_object) VALUES ('" . json_encode($php_object). "')"; Any idea which is faster serialize() / unserialize() or json_ecode() / json_decode()? Hey guys!, Any help is greatly appreciated! what i want to do is store a link to a pdf file which will open the file when clicked. just now when clicked will only open the file name but not with the extension .pdf? Thanks! Hi! So I'm fairly new to PHP, and am currently making a website from scratch including as much PHP functionality as I can for learning purposes. As I have just finished making a blog function, I started to wonder. Is it normal to store every part of a website in a the database? The blog part of the website I just created has of course all the differet blog entries stored in a table in the db, but is it also normal practice to store about, contact etc. in tables too? Or should categories like these be created using brand new .php documents? I am in the progress of making a page controller and thought I should clearify things first, before I go any further. This question may seem stupid, but I don't know alot about what the normal practices of doing things like these in php are. Anyways, hope someone can help me out! Hi, I'm trying to store the first+lastname from my mysql user datababase into arrays like this: // Fill up array with names $a[]="Anna"; $a[]="Brittany"; $a[]="Cinderella"; $a[]="Diana"; $a[]="Eva"; $a[]="Fiona"; $a[]="Gunda"; $a[]="Hege"; $a[]="Inga"; $a[]="Johanna"; $a[]="Kitty"; $a[]="Linda"; $a[]="Nina"; $a[]="Ophelia"; $a[]="Petunia"; $a[]="Amanda"; $a[]="Raquel"; $a[]="Cindy"; $a[]="Doris"; $a[]="Eve"; $a[]="Evita"; $a[]="Sunniva"; $a[]="Tove"; $a[]="Unni"; $a[]="Violet"; Is there a recommended BEST PRACTICE for storing (and retrieving) telephone numbers from a database table? Is it best to store (in the USA) the area code separate from the rest of the number? Remove parenthesis and/or dashes? Or is there no reason to concern myself with performance or hacking issues regarding the storage of phone numbers as 323-555-1212 or (323)555-1212 inside my table? Hi, I have this form which will create a checkbox list using data from my database and also determin if a checkbox had been checked before and check if it had. <form style="text-align:center" name="PrefRestaurant" id="PrefRestaurant" action="preferances_check.php" method="post"><table align="center"> <?php checkbox(id, name, restaurants, id); ?></table> <input type="submit" name="Prefer" id="Prefer" value="Επιλογή"/></form> function checkbox($intIdField, $strNameField, $strTableName, $strOrderField, $strMethod="asc") { $strQuery = "select $intIdField, $strNameField from $strTableName order by $strOrderField $strMethod"; $rsrcResult = mysql_query($strQuery); while ($arrayRow = mysql_fetch_assoc($rsrcResult)) { $testqry = "SELECT * FROM user_restaurant WHERE user_id = $_SESSION[UserId] AND restaurant_id = $arrayRow[id]"; $rsltestqry = mysql_query($testqry); $numrows = mysql_num_rows($rsltestqry); if ($numrows == 1) { echo "<tr align=\"left\"><td><input type=\"checkbox\" name=\"restaurant[]\" value=\"$arrayRow[id]\" checked/>$arrayRow[name]</td></tr>"; } else{ echo "<tr align=\"left\"><td><input type=\"checkbox\" name=\"restaurant[]\" value=\"$arrayRow[id]\" />$arrayRow[name]</td></tr>"; } } } Now the part which I can't get to work is when I'm trying to store the new values in my database. When I click the submit button I clear my database of any row that is related to the currently loggedin user and I want to store his new preferences (checked cheboxes). I've read that only the cheked checkboxes' values are POSTed so I did this (preferances_check.php) foreach($_POST['restaurant'] as $value) { $query="INSERT INTO user_restaurant VALUES ('$_SESSION[UserId]','$value')"; } But it is not working, nothing gets written in my table Could someone please enlighten me on this? Thnks! Hi Guys, I have been contacted by a client who wants me to develop an application which performs the following functionality: Lets say the domain name is xyz.com . We provide an email of our domain to the person who signup on our website for our services. Lets say the email that is given to the customer is email@xyz.com The client wants to built PHP application in which if an email is sent to email@xyz.com it gets downloaded and is stored in the MySql Database. After the download there is going to be a set of algorithms which will decided whether to forward this email to the client or not on his email address. I have no idea how to accomplish this functionality. Any suggestions would be appreciated. Thanks Sadan Masroor. Hey, i need help storing an image in my database via the URL(image location) at the moment my php code is storing the image in a folder on the directory called upload. here is the code: <?php // Where the file is going to be placed $target_path = "upload /"; /* Add the original filename to our target path. Result is "uploads/filename.extension" */ $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); $target_path = "upload/"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename $_FILES['uploadedfile']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?> Click <a href="products.php">HERE</a> to go back to form if someone could help me i'd be very grateful Hi, my goal is to be able to create a web based interface for someone who has no programming skills or interest to be able to maintain a list of usernames and passwords for protecting a page of links on a website. so, I've created a page that can write to a database, and I can see that it is working, I can read entries, etc. now, I need to know how to make a script that will check against that database for valid UN/PW combinations. what is the best method for this? James Hi, I'm building a webshop and im stuck at the checkout. I'm using this Shopping Cart class http://www.webforcecart.com/manual.html The cart is stored as an object in $_SESSION[cart]. This method Code: [Select] print_r($cart->get_contents());would get this as output: Array ( => Array ( [id] => 7 [qty] => 1 [price] => 11.00 [info] => Test [subtotal] => 11 ) [1] => Array ( [id] => 6 [qty] => 2 [price] => 19.00 [info] => White 0 [subtotal] => 38 ) ) In the table Order I would like to store order-id customer-id total products total quantity total price date In the table Orderrow I would like to sto order-id, product-id, product-name, quantity, price, subtotal I know i can get the order-id with the function mysql_insert_id() but how can i store each product in the array with their info in the table Orderrow? Or is there a better way to do this? please advice me, thank you. I am building a project that requires I store query strings in a table (stage_reqs) which are called to determine permissions. These strings will look something like this: Code: [Select] select salesman from jobs where salesman is not NULL and job_id='".$this->job_id."' limit 1 The variable value needs to be determined from within the function it is being accessed in. Can I use eval to do this? Thanks, Chris Hello people, I have created an application in Code Charge where my site users can login and play games online.The game code is run via flash and html. The Game has 5 stages and from a page in my application called transfertogame.php , i transfer them to the game page. Now i want to be able to track each players progress via database so that when they log back in and they get to the transfertogame.php page, it can check the page they were on before and immediately take them to the page without starting from page 1. Any help will be appreciated as i am very poor with php scripting This is the session ID i guess is being used from my application page //Initialize Method @4-537EA73F function Initialize() { if(!$this->Visible) return; $this->ds->Parameters["sesUserID"] = CCGetSession("UserID"); } //End Initialize Method //Validate Method @4-7E1FC38C function Validate() { $Validation = true; $Where = ""; $this->CCSEventResult = CCGetEvent($this->CCSEvents, "OnValidate"); return (($this->Errors->Count() == 0) && $Validation); } //End Validate Method |