Jump to content

Psycho

Moderators
  • Posts

    12,147
  • Joined

  • Last visited

  • Days Won

    127

Everything posted by Psycho

  1. Huh? The "true" I was referring to was the one used as the third parameter in the in_array() function. That is specifically used to make the in_array() comparisons strict. If you use it then "2013" will not match 2013. But, if you leave it out (or make it false) then the string "2013" will match the number 2013. But, what are you wanting $aSearch to be the index of the $years array when you already have the actual year value?
  2. OK, after reviewing all the code, I've found some other opportunities for improvement. The code to create the array for years is overly complicated. Instead of using date() and strtotime(), just use date() to get the current year and subtract one. strtotime() is inefficient. Plus, you don't need a loop, just use range() //Build the years array using current year -1 and 4 yerars forward $startYear = date(Y) - 1; //Start Year $years = range($startYear, $startYear+4); I don't know what clean() is doing, but all it really needs to do is trim() the value since you are doing all the validations inline. empty() can replace the empty string and null check. But, you don't need it anyway since the is_numeric() check would return false anyway. And, you don't need the is_numeric() since you are testing against the valid years. Just a lot of unnecessary code. Also, even if you fix the array_search() described above, the condition would still return true because you are assigning the result of in_array() to the variable $aSearch. So, you are really testing if you can assign a value to $aSearch - which will always return true. I would also change the variable $curYear to $selectedYear since it would not necessarily be the current year. This should be all that you need //Build a valid years array using current year -1 and 4 yerars forward from that $currentYear = date(Y); //Start Year $validYears = range($startYear-1, $startYear+4); //In order for us to make sure we have clean parameters for our jQuery calls later //We have to make sure that our year variable usage is consistant throughout. //If our case, we are passing the full 4 digit year as am INT = $curYear $selectedYear = clean($_GET['curYear']); print "Before anything: curYear = $curYear <br><br><br>"; //Check if the selected value is a valid year, if not set to current year if(!in_array($selectedYear, $validYears)) { $selectedYear = $currentYear; } //Should be a good year for our calendar by this point. print "valid year<br>" . $years[$aSearch]; exit;
  3. The logic is kind of "wonky". You have the valid test as part of one of the conditions. I would suggest having all the tests be for invalid conditions, then if all of those come up false the result should be it is a valid year. But, the problem is the last condition check elseif($aSearch = in_array($curYear, $years, true)){ print "valid year<br>" . $years[$aSearch]; //It isn't in our array of valid years //$curYear = date(Y); } Why did you use true for the last condition? Do you realize what it does? It is for performing a strict comparison. I.e. The string "2013" will not match the number 2013 using a strict comparison. You don't show what the function clean() does, but the value you are passing it (from the $_GET array) is a string. I suspect you are not converting the value to a number. But, the values you added to the array $years are all numeric values.
  4. As explained above, there are many problems with trying to lock by IP addresses. Plus, anyone who knows what they are doing could simply use a proxy to get around the locks. But, if you are really intent on going forward there is a simple solution. In the attempts table create a column to store a timestamp - have it auto-populated for new records so you don't have to add it on INSERT. Then create a NEW record on every attempt - or only failed attempts, depending on your needs. Then you can simply run a query based on number of attempts within the last X minutes. If the count is >= 3 then don't allow the new attempt.
  5. The code is basing the shipping solely on the weight of the products. So it is assuming that the product is either A, B or C base don the weight. That is a very poor way of doing this. You should identify the products explicitly using a product ID or something like that. Plus, you should rethink how you define your logic. Instead of $8.00 for the first instance and $2.50 for each additional it would probably be easier to look it as a base rate of $5.50 if there are any units and $2.50 for every unit. You still get the same outcome, but the logic is a little easier to decipher in my opinion. You can give this a try - I give no guarantees <?php header('Content-Type: application/json'); $json = file_get_contents('php://input'); $request_body = json_decode($json, true); if (is_null($request_body) or !isset($request_body['eventName'])) { header('HTTP/1.1 400 Bad Request'); $response = array("rates" => ""); die(json_encode($response)); } switch ($request_body['eventName']) { case 'shippingrates.fetch': // ============= recieve data from cart ============== $country_code = $request_body["content"]["billingAddressCountry"]; $state_code = $request_body["content"]["billingAddressProvince"]; $isInternational = ($country_code != "US"); //Define description $description = ($isInternational) ? "International Shipping" : "USPS Standard Shipping"; //Define needed variables $maxWeight = 0; $unitCost = 0; $fixedCost = 0; //Calculate per unit shipping cost if($request_body["content"] && $request_body["content"]["items"]) { foreach ($request_body["content"]["items"] as $cart_item) { //Create variables for quantity and weight $quantity = $cart_item["quantity"]; $weight = $cart_item["weight"]; //Determine max weight of individual item $maxWeight = max($maxWeight, $weight); //Calculate unit shipping cost if($weight >= 300) { //Add unit cost for 300g+ products $unitCost += $quantity * 2.5; } else if($weight >= 200) { //Add unit cost for 200g+ products $unitCost += $quantity * 1; } else { //Add unit cost for less than 200g products $unitCost += ($isInternational)? 20 : 8; } } } //Calculate fixed shipping cost if($maxWeight >= 300) { $fixedCost = ($isInternational) ? 8.5 : 5.5; } else if ($maxWeight >= 200) { $fixedCost = ($isInternational) ? 9 : 5; } //Calculate total cost $totalCost = $fixedCost + $unitCost; // =========== return data to cart =============== $rates = array( array( "cost" => $totalCost, "description" => $description ), ); $response = array( "rates" => $rates ); header('HTTP/1.1 200 OK'); echo(json_encode($response)); break; default: header('HTTP/1.1 200 OK'); break; } ?>
  6. If you are wanting to find every instance of "Luas bangunan: xxx", then preg_match() is what you want. But, your title indicates you want to explode the string. If that is what you want to do, then you would use preg_split().
  7. Um, copy the file to the location you are trying to access it?
  8. Those are just Notices, which would usually be suppressed in a production environment. But, it's always a good idea to have them turned on when writing code. Basically, that warning means that you are trying to reference a variable which has not been defined yet. I'm not sure why you are getting that first error since you define $year directly before the line with the error: $year = $_POST['year']; $year = validateInput($year,"Birth Year"); If anything you would get an error on that first line if $_POST['year'] wasn't defined. BUt, there are problems with the logic. Never assume just because one value was POSTed (i.e. 'submit') that all the values were posted. It's always best to explicitly check. Such as $year = isset($_POST['year']) ? $_POST['year'] : false; //Then perform error logic if $year is false There are other logic problems as well. For example, the switch() statement is completely unnecessary. Just verify it is an int between 0 and 11 then use the value as the index of the array.
  9. Forget what I said before, dashes are used for comments. But, the semi-colon is still probably problematic. But, if I am reading that correct, you are also running two separate queries. Start with a simple query, that works, then add the additional complexity to get the specific data you need.
  10. The string for the query starts with a semi-colon which causes it to interprets the first line as a comment. Therefore, it sees the beginning of the actual query as a left parenthesis ;WITH TOTAL_KWH_WINTER AS (
  11. If you are at least making an attempt, people will be more willing to help you. I'm a bit confused by your use of the terminology "relational algebra". Seems like you are simply wanting to run a query - don't see what algebra has to do with it. I would start with the last problem. I think it is the easiest.
  12. I think the problem may be that you expect that the value in the POST data will tell you if it is checked or not. When you are dealing with a checkbox with a unique name, the value is typically irrelevant. The reason is that only CHECKED checkboxes are returned in the POST data. So, simply checking if the POST value for that field isset() is enough to tell you if it was checked or not. $obcDisplay_PostValue = isset($_POST['obcDisplay']) ? 1 : 0; //Insert this value into the DB.
  13. As a side note: Instead of using a string value of 'Y' or 'N' that you then need to test, it is more efficient to use 1 or 0 since those can logically be interpreted as the Boolean TRUE/FALSE values. <?=($r['obcDisplay']) ? 'checked="checked"' : ''; ?>
  14. You may want to consider trim()ing the values before that check. Otherwise, a value of only white-space characters (such as spaces) would cause empty() to return true.
  15. Yes, you would determine ALL the relevant data needed in PHP and then pass the results back to the AJAX call and do whatever you need to using JavaScript. That's the correct way to do it and maintain separation of business logic and data. However, there is a simpler way. On your page identify the different containers to hold the dynamic content. I would assume, for example, that you would have a container for the grid and another for the pagination controls. You could use the PHP logic to build the HTML content for those containers and then pass them back to the AJAX call and simply drop those pieces of content into the appropriate containers.
  16. Not at all. I'm saying the PHP code should get all the data you need: total records, total pages, current pages, etc. AND the data to display on the current page. You can then put all the data into an array and then pass it in JSON format back to the calling AJAX request. Then use JavaScript to tear apart the data and populate/enable/disable the pagination controls, the grid, etc.
  17. I would return all the requisite data in JSON format. Then use JavaScript to populate the page and set the necessary pagination controls. I'd suggest the data should be sent as a multi-dimensional array something like this: $return = array( 'page' => 2, 'total_pages' => 10, 'page_data' = array( 0 => array(data_for_first_record), 1 => array(data_for_second_record), 2 => array(data_for_third_record), . . . ) )
  18. If you are certain that you will never use this page for others to view the user's listing (even an administrator), then you don't even need to pass the ID on the query string. Just get the ID from the session data. If you DO want to have the ability for an admin to view the page of a user then go ahead and keep it in the URL and do a check to see if the user requesting the page has the same ID as the one they are requesting OR if the user is an admin. Rough example: if($_SESSION['user_id'] <> $_GET['user_id'] || $_SESSION['admin'] != 1) { echo "You do not have rights to view the page."; //perform error logic and / or redirect the user to another page. }
  19. I think you are making this way more difficult than it needs to be. On the form to submit a listing you have a hidden field for submittedby <input type="hidden" name="submittedby"> . . . BUT it has no value! Since it is hidden the user cannot enter a value either (at least not normally). Then on the processing page you attempt to use that field when saving new records $submittedby = $_POST['submittedby']; // . . . $sql = "INSERT INTO privatelistings (submittedby,listingtitle,make,model,exteriorcolour,enginesize,fueltype,yearregistered,transmission,mileage,nodoors,bodystyle,price,photo,photo1) VALUES ('$submittedby', '$listingtitle', '$make', '$model', '$exteriorcolour', '$enginesize', '$fueltype', '$yearregistered', '$transmission', '$mileage', '$nodoors', '$bodystyle', '$price', '$pic1', '$pic2')"; Unless I am missing something that "submittedby" value in the inserted records will be empty. So, your code to retrieve records using a LIKE on the submittedby will not find any results. Everything is backwards. I will assume that users must log in to use the site, therefore there would have to be some way to track that a user is logged in. I will further assume that you have the userID value in session data. Assuming this is all true, this is how you should be approaching this: 1. No input field is needed for the submittedby on the forms. 2. On the page that processes the form submissions, use the session value for the userID in the INSERT query to associate the listing with the user who submitted it. 3. On the profile page use a value on the URL to identify the user for which the page should be displayed. You don't say if users can view other users pages or not. But, I'll assume that you will at least allow an admin to view others' profile pages. If you want to restrict users from seeing other users' pages you can checked the logged in userID to the userID of the requested page. So, on the profile page, use the userID passed in the URL (i.e. $_GET value) to query the listings associated with that user. You would only use LIKE in a query for 'search' type queries. Not where you want to see all records related to a specific key.
  20. OK, let's go over several things: 1. When you have input fields that should be "grouped", it is best (IMO) to ensure there is a provided index that will group them. Using just [] and "assuming" that the appropriate fields will have the same index is problematic. Plus, you have checkbox values and the data will get screwed up since unchecked fields are not included in the POST data and the indexed will get mis-matched! I also prefer to have a single multi-dimensional array instead of several flat arrays. That way you can process the data with a single foreach() loop. 2. What is this? if ($ltotal == '0.00'){ $lstatus = "2"; } else { $lstatus = "1"; } What is the significance of 1 and 2? Are these supposed to be some sort of true/false equivalent? If so, then you should use 0 and 1 as those will be interpreted as equivalents of the Boolean True / False. Plus, the ternary operator would work better for this as well. 3. You should not be using mysql_ functions they are long deprecated. 4. The code has separate logic for existing data vs. new data. That's a waste when you can do it all with one query using the ON DUPLICATE KEY UPDATE logic. 5. No need to create unique variables in the loop to create the form if you are only going to use them once. Just use the $row array values. 6. Don't use 'SELECT *', it is a waste. List out the fields you will use. 7. You have a readonly field for the total - but you use it in the UPDATE query. Why? Are you aware a user can override that readonly status? 8. The 'active' checkbox has a value of 0. Should be a 1 to be more logical. 9. You have description and lmarkup as part of the POST data processing, but there are no input fields for those values.
  21. Yeah, your post doesn't make sense. You state you want to show the listing made by a user on their profile page and you show the URL for that page which includes an ID parameter on the URL string for the user ID. Then you go on to show an input field used on the add listing page for 'submitted by". But, it is an input field, which means the user can type in any value. Shoudln't this be a hidden field using the user ID of the person submitting the listing (or get it dynamically on the processing page)? Then your page to display listings is apparently trying to find listing by the user submitted value for "submitted by". I assume then that you expect the uessr to enter the name of the person who submitted the values. If it was the user's page, then you would run a page to get the listings using the User ID. This looks more like a search of listings by a user - which has nothing to do with your original request.
  22. MoFish, You problem doesn't make sense. When you define an array value such as this array('staff_last_login'=>'NOW()') The quotes are used as delimiters to define where the value starts and ends. They are not part of the value. So, if you use that array value in generating your query, there will be no quotes. $data = array('staff_last_login'=>'NOW()'); $query = "UPDATE staff SET staff_last_login={$data['staff_last_login']} WHERE staff_id='1'"; echo $query; //Output: UPDATE staff SET staff_last_login=NOW() WHERE staff_id='1'
  23. My biggest question would be how is the data set up currently? Are each line in separate tables? Are those tables similarly constructed (i.e. same columns, at least for the same parameters)? If they are in the same tables or the tables are similar enough you can probably use what you have and create new procedures for performing the searches. But, even if the table structures are very dissimilar, you could run multiple "queries" on each product line in a single query to get the results from all lines using a UNION. A complete rewrite will be a huge task, but you would get better, cleaner code (assuming you do it right ). I would ask myself these questions. Aside from the new request are there other non-minor problems with the current functionality? How much time is spent currently maintaining the application? If there are problems for the users how much time or pain are these issues? If it's not broke don't fix it. Ugly inefficient code that works - still works. So, you have to weight the effort of the initial rewrite and the effort to clean up bugs that get missed during that process compared to the current pain to the users and the time you are investing to keep the current application running.
  24. A couple other things: 1. You should trim() the string. 2. You don't need to use a string of if/else statements since if any are true they will do a 'return' and exit the function 3. You can use a switch() to check the return value 4. Be careful of using '0' as a return value when many values can be returned because 0 can also be interpreted as the Boolean false. 5. Think about the order in which you perform the checks since a value can actually meet multiple error conditions. I would do min/max lengths before checking the format. Here are some changes in the logic that I think work better function CheckFullname($string, $minlen, $maxlen) { /* define error codes 100 = wrong pattern match 101 = string is too long 102 = string is too short 0 = empty input */ //Trim the string $string = trim($string); //Check for empty value if(!strlen($string)) { return 0; } //Check minimum length if(strlen($string) < $minlen) { return 102; } //Check maximum length if (strlen($string) > $maxlen) { return 101; } //Check fullname format if (!preg_match('/^(?:[\p{L}\p{Mn}\p{Pd}\'\x{2019}]+\s[\p{L}\p{Mn}\p{Pd}\'\x{2019}]+\s?)+$/u', $string)) { return 100; } // No errors detected return true; } // this function executed below is returning error code 100. $fullName = "John Doe"; $nameMinimum = 4; $nameMaximum = 40; $nameError = false; switch(Checkfullname($fullName, $nameMinimum, $nameMaximum)) { case 0: $nameError = 'Your name is required.'; break; case 100: $nameError = 'Please provide your full name without any funny characters.'; break; case 101: $nameError = 'Your name should be at most 40 characters long.'; break; case 102: $nameError = 'Your name should be at least 4 characters long.'; break; } if($nameError) { echo $nameError; } else { $fullname = safe($string); }
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.