-
Posts
5,449 -
Joined
-
Days Won
174
Everything posted by mac_gyver
-
here is the basic LOGIC you need to detect when to close the previous section, start a new section, and output data under a section - $departmentHeader=false; while( ... ){ $staffDepartment=$staff['department']; // detect a change in the department header if($departmentHeader!=$staffDepartment){ // the department changed (or is the first one) if($departmentHeader != false){ // not the first section, close out the previous section here... } $departmentHeader=$staffDepartment; // save the header // start a new section here... } // output the data under each section here... } // close out the final section here...
-
afraid not. if you are not at the point that you will even make an attempt, you are not yet ready to leave the temple, grasshopper...
-
one possible way of solving your assignment - $data['Joseph'] = array('loc'=>array('kitchen','livingroom'),'wep'=>array('rope','gun')); $data['Julie'] = array('loc'=>array('dining','bedroom'),'wep'=>array('gun','poison')); // ... other data as desired $wep = 'gun'; $loc = 'dining'; $found = false; foreach($data as $person=>$arr){ if(in_array($wep,$arr['wep']) && in_array($loc,$arr['loc'])){ $found = $person; break; // stop at first match } } if($found){ echo "$found did it."; } else { echo "No match."; }
-
whatever name you gave each check-box form field will be set when the check-box is checked and won't be set if it is not checked. you would then probably want to have a conditionally statement to produce a yes/no indication to insert into your email message for each check-box. php has an instruction to test if a variable is set, surprisingly its called - isset() $ck1 = 'no'; // default to no/not checked if(isset($_POST['your_check_box_name_1'])){ $ck1 = 'yes'; } $ck2 = 'no'; // default to no/not checked if(isset($_POST['your_check_box_name_2'])){ $ck2 = 'yes'; } // then just include the $ck1,$ck2 strings when building your email message "some legend for check-box 1: $ck1" . $content_nl . "some legend for check-box 2: $ck2" . $content_nl .
-
// calculate current_page +/- 4, limited by 1/total_pages $start = max(1, $current_page - 4); $end = min($current_page + 4, $total_pages); // if start resulted in 1, make end = start + 8 if($start == 1){$end = $start + 8;} // if end resulted in total_pages, make start = $end - 8 if($end == $total_pages){$start = $end - 8;} // limit start/end to 1/total_pages $start = max(1, $start); $end = min($end, $total_pages); for($p = $start; $p <= $end; $p++) { if($p == $current_page){ echo "[$p] "; // current_page not a link } else { echo "<a href='?p=$p'>$p</a> "; } }
-
if you use array_slice(), it will return the portion of your master array that you want. you can then just loop over that portion of the array using a foreach() loop. the offset and length parameters for array_slice() should be your existing $start and $page_size values.
-
Simple serialized (?) string not being unserialized
mac_gyver replied to newsomjk's topic in PHP Coding Help
your code works for me. best guess that code is inside of some other output that is hiding it in the 'view source' in your browser. btw - if you truly want an array as a result, use a true value as the second parameter in $array = json_decode($str,true); -
class variables are referenced inside their class using $this->variable_name, like you are doing in the class ClassVar. $new_varname is just a local variable that only exists inside the __construct() function. it is not a class variable (likewise for the $newConnect variable in the first class.)
-
there are many different kinds of crazy. does your computer jump off of the table and run into the kitchen and grab a knife or what? hint: we are not standing right next to you and don't know what you saw. you must communicate clearly what happened in order to get help with it.
-
echo actually does accept a comma separated list of arguments.
-
your syntax for the insert query is incorrect and you are not testing if the query failed due to an error. there is no WHERE clause in an insert query. it appears you are trying to use the INSERT ... SET ... syntax - INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name SET col_name={expr | DEFAULT}, ... [ ON DUPLICATE KEY UPDATE col_name=expr [, col_name=expr] ... ] also, AND is a logical operator. a comma , is used to separate a list.
-
first check if a form has been submitted using $_SERVER['REQUEST_METHOD'] == "POST". then both the $_FILES and $_POST array will be empty for that condition or you can check $_SERVER['CONTENT_LENGTH'] to get the same information that is output in that warning message.
-
that's all the more reason to NOT break encapsulation that is provided by functions. a function should only interact with the calling code at the point where the function is being called. if you read the calling code, you should be able to see what values are being supplied as inputs (the call time parameters), the function name itself indicates what the function does, and any result is returned at the point where the function is called. once you write and test your function, you should be able to forget what the actual code and variables in it are. it becomes a black box, reducing the amount of information you must actively keep track of when coding. by using global variables inside a function, you must now keep track of which functions use which variables and you can no longer tell just by looking at the calling code what inputs a function uses (a week or a month from now, this will be important because you will have forgotten exactly what you did in each function and you shouldn't need to remember exactly what you have done in each function.) this doesn't reduce the amount of information you must keep track of, it actually makes more work for you. an example using your checkvariable() function in the first post. a month from now, when you try (or someone else tries) to figure out what your code is doing, which would you rather see in your code - checkvariable(); // check what variable? i guess i'll need to find and read or remember what the checkvariable function is to find out. or checkvariable($_GET['checkvar']); // check the $_GET['checkvar'] in this call checkvariable($_POST['checkvar']); // check the $_POST['checkvar'] in this call
-
changing domain in all links -- mod_rewrite?
mac_gyver replied to severndigital's topic in Apache HTTP Server
the links you output on your page must point to where your web site is hosted. mod_rewrite has nothing to do with what you are outputting. mod_rewrite determines what happens when your server receives a request for a page. if old.dyndns.org still points to where your web site is hosted, mod_rewrite could be used, but it doesn't sound like that is what you need. -
if there is no row for a vehicle, there's nothing for your while(){} loop to loop over and the code inside your while loop doesn't even run. also, since there's no row, there are no values for $value_nc, $value_tr, and $value_vs and trying to access them would produce errors. what do you want the output to be in this case? a message, just zeros for those values,...? however, you should never run SELECT queries inside of loops. you should run ONE query that gets the rows you want. the following example code (untested) queries for the rows, then loops over the values in the $array and outputs whatever you want when there is no row or the data from the query if there is a row - $keys = implode(',',array_keys($array)); // get the keys as a list to query for $query = "SELECT * FROM weapon_kills WHERE character_number=$char_id AND vehicle IN($keys)"; $data = array(); foreach($dbh_beta->query($query,PDO::FETCH_ASSOC) as $row){ $data[$row['vehicle']] = $row; // store each row using the vehicle as the key/index } foreach ($array as $key => $value){ if(!isset($data[$key])){ // no vehicle, output whatever you want for that case... echo "<td colspan='3'>The vehicle $key:$value doesn't exist.</td>"; } else { // the vehicle exists in the table $row = $data[$key]; $value_nc = $row["value_nc"]; $value_tr = $row["value_tr"]; $value_vs = $row["value_vs"]; if($faction === "nc"){ echo "<td>".number_format($value_tr + $value_vs)."</td> <td>".number_format($value_tr)."</td> <td>".number_format($value_vs)."</td> "; } elseif ($faction === "tr"){ echo "<td>".number_format($value_nc + $value_vs)."</td> <td>".number_format($value_nc)."</td> <td>".number_format($value_vs)."</td> "; } elseif ($faction === "vs"){ echo "<td>".number_format($value_nc + $value_tr)."</td> <td>".number_format($value_nc)."</td> <td>".number_format($value_tr)."</td> "; } } }
-
Total off by penny - can't figure out how
mac_gyver replied to learningcurve's topic in PHP Coding Help
off topic for this thread, but the following is an example of a data driven design, where you have your product data defined somewhere (array, database table) and your main code simply loops over the products. the code is generic and there's no product specific reference in the code at all (eliminating all those long variable names to keep track of which product the value is for.) this separates the code from the data and eliminates any replicated code for each product. if you need to change anything about the products (add more, rearrange the display order, change a tile...), all you do is change the data definition. the main code isn't touched and if you need to change the html markup, it only exists once. you can run the following in a .php file by itself to see how it works - <?php //some madeup values for testing - $JECTindividual_print_price['base']['United States'] = 10.00; $JECTindividual_print_price['base']['Canada'] = 11.00; $JECTindividual_electronic_price['base'] = 5.00; $JECTindividual_combo_price['base'] = 12.00; // define the product choices $product['JECT'] = array('title'=>'Journal on Excellence', 'price_us_print'=>$JECTindividual_print_price['base']['United States'], 'price_can_print'=>$JECTindividual_print_price['base']['Canada'], 'price_electronic'=>$JECTindividual_electronic_price['base'], 'price_combo'=>$JECTindividual_combo_price['base'] ); $product['JCTL'] = array('title'=>'Journal on Centers', // replace following with actual amount variables, these are just a copy of JECT values for demo purposes 'price_us_print'=>$JECTindividual_print_price['base']['United States'], 'price_can_print'=>$JECTindividual_print_price['base']['Canada'], 'price_electronic'=>$JECTindividual_electronic_price['base'], 'price_combo'=>$JECTindividual_combo_price['base'] ); $product['LCJ'] = array('title'=>'Learning Communities', // replace following with actual amount variables, these are just a copy of JECT values for demo purposes 'price_us_print'=>$JECTindividual_print_price['base']['United States'], 'price_can_print'=>$JECTindividual_print_price['base']['Canada'], 'price_electronic'=>$JECTindividual_electronic_price['base'], 'price_combo'=>$JECTindividual_combo_price['base'] ); // "carefully" use extract to populate program variables for testing - if(isset($_POST['redo'])) {extract($_POST);} // start of form for testing - echo "<form method='post'>"; // produce the form fields for the product choices - foreach($product as $key=>$prod){ echo "<font size='+1'> <h3><b><em>{$prod['title']}</em></b></h3> </font> <input type='radio' name='choice[$key]' value='no' ".(!isset($choice[$key]) || $choice[$key]=="no" ? 'checked' : '')."> No thanks</br> <input type='radio' name='choice[$key]' value='print' ".(isset($choice[$key]) && $choice[$key]=="print" ? 'checked' : '')."> Print subscription (US and Canada only): US \${$prod['price_us_print']}, Canada \${$prod['price_can_print']}</br> <input type='radio' name='choice[$key]' value='electronic' ".(isset($choice[$key]) && $choice[$key]=="electronic" ? 'checked' : '')."> Electronic subscription (access to complete online archive): \${$prod['price_electronic']}</br> <input type='radio' name='choice[$key]' value='combo' ".(isset($choice[$key]) && $choice[$key]=="combo" ? 'checked' : '')."> Combination print and electronic subscription (US and Canada only): \${$prod['price_combo']}</br> <p style='text-indent:30px;'>Length of subscription:</br></p> <label><input type='radio' name='sub[$key]' value='1' ".(!isset($sub[$key]) || $sub[$key]=="1" ? 'checked' : '')."> 1 year</label></br> <label><input type='radio' name='sub[$key]' value='2' ".(isset($sub[$key]) && $sub[$key]=="2" ? 'checked' : '')." > 2 years</label></br> <label><input type='radio' name='sub[$key]' value='3' ".(isset($sub[$key]) && $sub[$key]=="3" ? 'checked' : '')."> 3 years</label></br> <label><input type='checkbox' name='renewal[$key]' value='yes' ".(isset($renewal[$key]) && $renewal[$key]=="yes" ? 'checked' : '')."> Check box if this is a renewal</label></br> "; } // submit button for testing - echo "<input type='submit' name='redo'></form>"; ?> because the form fields have been changed to array names, any code referencing them would need to be changed to match. since the data is submitted as arrays to the form processing code, that code would simply loop over the data, not repeat the blocks of code for each different product. -
forget that you ever saw the GLOBAL keyword. it is only used inside of a function definition. if putting GLOBAL $var; in your main code made that variable appear inside of every function, you would need to keep track of every variable name used in every function in your application to avoid reusing one of them. the correct way of getting a value (variable, string, result of another function call) into a function is to pass it in as a call time parameter when you call that function - checkvariable($checkvar); // call your function with the parameter you want to supply it with as an input function checkvariable($var) { var_dump($var); }
-
Total off by penny - can't figure out how
mac_gyver replied to learningcurve's topic in PHP Coding Help
the total submitted to the php code is in the total javascript variable. but you have two totals, one in total_hidden and one in total. if you use alert(total) does it give you the displayed/correct total or the incorrect/php code value? [you also have TOO much code] - you apparently have an array holding the discounted amounts and you are also calculating the discount and subtracting it from the total. i suspect the error is in the two uses of values. edit: more detailed answer - the total_hidden will always be true (did i mention you have TOO much code) if any subscription has been selected. total_hidden is calculated from the javascript array of values and it is what you display in the form as the Grand Total: however, the total that you submit in the form field is calculated/subtracted in the javascript code and is likely suffering from a floating point conversion error. total and total_hidden should be the same, i.e. you don't need two times the variables/code/data/calculations to do this. -
an introductory programming book, tutorial, class,... is only going to show the basics and maybe mention the need for security and application level error checking/reporting/recovery logic. it should really be the other way around. start by teaching the need for security and checking for problems at each step that can fail, then teach how to write logic that does something. the threads/problems you have been posting are due to two things - 1) old depreciated/superseded features (most of which were depreciated/superseded in the years 2001/2002 and since then there have been very few changes that are not backwardly compatible for most code) that must to be updated to current standards to even work on current or near future php versions. there are migration sections in the php.net documentation that list what has actually been changed in each major php version. reading these might help you. they are in the php.net documentation appendix and can be found by searching for "php migration". the php change logs (one for php4 and one for php5) also have sections listing the actual changes for each version along with bugs that were fixed. 2) minimalistic code that just barely 'works' when everything is perfect, but vomits when the least little thing isn't right and doesn't tell you when, where, or what is wrong that caused it to vomit. writing code that doesn't produce fatal-errors/warnings/notices each time it runs takes time to write. even if the error messages are hidden due to php settings, php is still detecting all these errors when the code runs. the error_reporting and display_errors/log_errors settings only determine what happens when an error is detected. is it reported and if it is reported, is the message displayed or logged? a lot of live servers have php's error logging turned on and is not uncommon to see GIGABYTE size error log files that eventually take up all the free disk allotment due to php code that produces 100's of warnings/notices each time it runs. also, since hackers can easily cause minimalistic code to produce errors by feeding it data that isn't prefect, if display_errors are turned on, this gives hackers important information about the directory structure and account names and if using things like mysql_error() in your code, being able to trigger database errors exposes the database hostname and username to the hacker. for item #1, you must fix this things for the code to run. for item #2, time to pay the Piper.
-
the current error was ALWAYS occuring at the extract statement when the query didn't return any rows, but the reporting or display of the final step, the error message, was being hidden due to the error_reporting and/or display_errors settings. the extract statement producing that error when there's nothing to extract doesn't have anything to do with the php version. saidly, php actively promoted hiding errors as a way of letting non-coders produce code that 'worked' without it actually being good code. the time someone saved when they were writting this script, in not checking if the query returned a row or not, is being spent by you now in just finding out why the code is producing the errors. for the current error message, if you ignore the error message, does the code actually do what you expect when the username isn't found in the database table? the extract statement is failing and it is not creating the $familyid and $email variables. does the code take an expected execution path and produce the expected result when those variables don't exist? the suggestion i gave to test if the query actually matched a row in the database before attempting to use that data and to output a message when there is no matching data will cause the code to take an expected execuition path regardless of if the query did or didn't match the username. i.e. the code will always do something and tell you what it is that it did. there won't be any blank pages or guessing about what the code is doing. this is how good code is written and how this code you are fighting with should have been written in the first place.
-
for that specific code, it means that the query matched no rows. the code is checking if the query execuited (the or die(...) logic), but is not testing if the query matched any rows before trying to fetch and use a row from a result set that doesn't have any rows. ideally, the logic should test if mysql_num_rows($result) > 0 to see if the query returnd any rows before attempting to fetch and use any of the data in the result set and if that test if not true, output an appropiate message (i.e. username not found) and skip over any logic that is dependent on the query matching a username.
-
do you have php's error_reporting/display_errors turned on? i get php warnings (whcih could be due to copy/pasting the text of your xml out of the forum) about - Document labelled UTF-16 but has UTF-8 content beyond that, you would probably need to post your code.
-
Calling events from an array within a loop from a function
mac_gyver replied to fife's topic in PHP Coding Help
the format of the value in $event_day doesn't match what you are retreiving in the query. they must have exactly the same format (with leading zeros on the month and day and the same day format) for any kind of comparison to work. your query is also getting the day with the st, nd, rd..., which you probably don't want or need and which also won't match just the incrementing day number. also, since you are doing increment/decerments on the month to make the links, you are lossing the leading zero in the links. your best bet to format $event_day regardless of the input values would be to use - $event_day = sprintf('%04d-%02d-%02d',$year,$month,$list_day); -
that would indicate that either you don't have php installed/functioning on your web server OR you opened the form as a file directly in your browser rather than browsing to the URL of your form page and it didn't actually submit to the URL of your form processing code.
-
you do know that mysql has a query cache? have you checked if it is turned on and has enough memory available? also, your series of performance questions indicates you likely have an issued in your application logic that you need to fix before you can worry about caching, otherwise you are just putting bandaids on top of a problem.