Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
Yes, it's absolutely possible. If you can put something into an HTML page - then it can be built dynamically via PHP. You say you know how to query the DB and get the results. Just iterate through those results and build the select list. I usually have a function to build dynamic select lists instead of coding them individually. //Function to build select options based on passed array function buildSelectOptions($options) { $optionsHTML = ''; foreach($options as $id => $label) { $optionsHTML .= "<option value='{$id}'>{$label}</option>\n"; } return $optionsHTML; } //Run query to get the ID and Name from the table //Then populate into an array $sth = $dbh->query('SELECT id, country FROM countries'); $sth ->setFetchMode(PDO::FETCH_ASSOC); $countries = array(); while($row = $sth->fetch()) { $countries[$row['id']] = $row['country']; } //Create select list options $countryOptions = buildSelectOptions($countries); //Later in the HTML for the page <option name="country"> <?php echo $countryOptions; ?> </option>
-
As I said, when I copied all your files down locally it doesn't happen. I only see the problem when viewing your page at the URL provided. Doesn't make any sense. Maybe I missed something, but I don't think so. I dig into the JavaScript code, but it could possibly be referencing something that is causing it. You could also try using a margin of -1 in the above (it should just need to be margin-top or margin-bottom). But, I would consider that as a kludge solution.
-
if($eyecolor !== "none" || $eyecolor !== "Blue" || $eyecolor !== "Brown" || $eyecolor !== "Green" || $eyecolor !== "Grey"){ $echo "Not an eye color"; } When you are doing NEGATIVE comparisons you have to be very careful about your AND/OR operators. No matter what the value is of $eyecolor that condition will always be TRUE. Let's just reduce that to two conditions if($eyecolor !== "none" || $eyecolor !== "Blue") Let's say the value of $eyecolor is "foo". That does not equal "none" and it does not equal "Blue", so the result of the comparison is TRUE. Now, let's say the value of $eyecolor is "Blue". Well, it doesn't equal "None" but it does equal "Blue". however, the result of that comparison is still TRUE! Because the comaprison is where the value does not equal "none" OR it does not equal "Blue". Since the first comparison is TRUE then the result is TRUE. The comparisons should use an AND to test for a value that does not match any of the value. But, a much simpler solution is to simply use an array of valid values. if(!in_array(strtolower($eyecolor), $validEyeColors)) { $echo "Not an eye color"; }
-
Odd. When I download all your content locally (htm, css, js & images) there is no gap. But, I do see the gap on your hosted site. I was able to simulate the gap by inserting a margin into the css code for the UL. So, it may have a default of 1px margin. Try adding an explicit 0px margin #nav li ul /* Default location */ { position: absolute; width: 101px; left: -300px; border-width: 1px; border-left: 0px solid; border-right: 0px solid; padding-left: 0px; margin: 0px; <<== ADD THIS LINE }
-
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?
-
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;
-
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.
-
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.
-
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; } ?>
-
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().
- 5 replies
-
- explode based on string
- regex
-
(and 3 more)
Tagged with:
-
Um, copy the file to the location you are trying to access it?
-
Are donations to specific users okay?
Psycho replied to Monkuar's topic in PHPFreaks.com Website Feedback
Do you need my paypal details? -
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.
-
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.
-
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 (
-
Relational algebra expression for given queries in simple database
Psycho replied to sherlockxhouse's topic in MySQL Help
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. -
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.
-
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"' : ''; ?>
-
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.
-
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.
- 12 replies
-
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.
- 12 replies
-
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), . . . ) )
- 12 replies
-
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. }
-
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.
-
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.