Psycho
Moderators-
Posts
12,159 -
Joined
-
Last visited
-
Days Won
130
Everything posted by Psycho
-
Yeah, I asked the same thing on a previous post of his. And instructed that it is not doing what he thinks it is doing and that he should remove it. I think he may be one of those people that likes to ask for help but then never actually listens.
-
Rather than try and "find" the ones that don't match, it would be easier to just replace ALL the ids with the $id you want. $id = '123'; $string1 = "<li id=123_test_[1]> <li id=123_test_[4]> <li id=567_test_[9]> <li id=123_test_[6]>"; echo preg_replace("#id=\d+_#", "id={$id}_", $string1); Ouput: <li id=123_test_[1]> <li id=123_test_[4]> <li id=123_test_[9]> <li id=123_test_[6]>
-
https
-
<?php //Create variable for the number of columns to use $max_columns = 5; //Create and run query $query = "SELECT DIST_PART_NUM FROM $tablename"; $result = mysql_query($query) or die(mysql_error()); //Put results into an array $records = array(); while($rec = mysql_fetch_assoc($result)) { $records[] = $rec; } //Determine rows needed $max_rows = ceil(count($records)/$max_columns); //Create the ouput $outout = ''; for($row = 0; $row < $max_rows; $row++) { //Open row $recordsHTML .= "<tr>\n"; for($col =0; $col<$max_columns; $col++) { //Determine value from array to use for this row/column $idx = $row+($col*$max_rows); $value = (isset($records[$idx])) ? $records[$idx] : ''; $recordsHTML .= "<td>$value</td>\n"; } //Close row $recordsHTML .= "<tr>\n"; } ?> <table> <?php echo $recordsHTML; ?> </table> EDIT: Fixed, but the last row will be used for all "offsets"
-
Do you need each record to go in it's own TD tags or can all of column one go in a TD tag, all of column 2 into another, etc.? The latter is much simpler, but the former isn't all that much more work.
-
NO, no one has to modify the bootstrap script. You simply create you applicatin so the bootstrap script is always called no matter what page is reqested. That script could set some default values (such as the example above), make the database connection, etc. Basically ANYTHING you want set/configured for every page. You would never want to add the same configurations to the top of every page because if there is ever a change you have to edit all those pages instead of just one. So, you could simply set the include path in this bootstrap file. As for $_PATHS it is not a system variable. In my example it is a variable that you would create (which is what I do).
-
You would have a configuration/settings file that is always called and that code would reside there. So, no matter what page is called you would have those default "paths" defined. Then include your files with somthing such as include($_PATHS['classes'].'somename.class.php'); include($_PATHS['settings'].'databaseconnection.php'); You can easily change the location of those "root" folders and just update that one config file. So, for the usersof your application as long as they install everything in the same relative locations it wouoldl all work.
-
Well, everything will be different based upon the particular needs of the validation taking place. Not everyone would validate, say, a phone number or date in the same way. YOU need to decide what data is valid for each field and build(find) the appropriate code. However, as an overall "process" for validation I will suggest that you validate ALL data for errors before determining the post is invalid. All too often I submit a form to be told that field #1 was invalid. When I fix that and resubmit I get an error that field #2 is invalid.
-
Take a look at the "notes" at the bottom of this page: http://www.phpguru.org/php-application-structure
-
Changing default select position due to MySQL result...
Psycho replied to ActaNonVerba1's topic in PHP Coding Help
<?php $selectedNoOfThumbs = mysql_result($data, 0,"NumberOfThumbnails"); $thumbOptionsList = array(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 25, 26, 27, 28); $thumbOptionsHTML = ''; foreach($thumbOptionsList as $thumbNo) { $selected = ($thumbNo==$selectedNoOfThumbs) ? ' selected="selected"' : ''; $thumbOptionsHTML .= " <option value=\"{$thumbNo}\"{$selected}>{$thumbNo}</option>\n"; } ?> <select name="numberofthumbnails"> <?php echo $thumbOptionsHTML; ?> </select> -
I'm not following your statements. On the code you attached, you are creating a form with a select field called "types" - there is a separate INPUT field called "Entry_Type" but since you did not specify a type property for that input I am assuming it is defaulting to a Text input. The form looks "OK". You are then POSTing that form to a processing page - is that processing page the same page? If so, there is nothing in the code that runs the query which does anything with $_POST['types'], which would be the value from that select list. The query does use $_POST['Entry_Types'] - but that is the misformatted input field not the select list. Are you referencing the wrong field?
-
Well "up to" is a loaded statement. I did some tests and found no more than 10%. But, you have to consider that is only 10% more that that one miniscule operation (were talking ~96 bytes per ternary vs. IF/ELSEin my tests). Granted you do need to consider that with respect to the traffic of your site. But, a sever *should* have billions of bytes available. There are other considerations as well. Not using a ternary operator will result in more verbose code that will increase the size of the php files on the physical disc and the time to read/parse those files. Again, that is a miniscule amount, but I'll use any excuse to keep my ternary operators. If I may use an expression: "You can tear my ternary operators from my cold, dead hands"
-
A slight modification to MatthewJ's code that is slightly better IMHO because you only have one statement to create the OPTION tag. By reducing the "branches" in the logic you get greater consistency and less bugs in your code. This assumes that $selectedValue for the record is already set. while ($rowvalues=mssql_fetch_array($getnames)) { $name = $rowvalues['forename']; $selected = ($name==$selectedValue) ? ' selected="selected"' : ''; $options.="<option value=\"{$name}\"{$selected}>{$name}"</option>\n"; }
-
The code you provide shows a select field (called 'types') which is populated from the database. Since you are using the same value for the option value and the option text I will assume that the options do have values. You are then apparently POSTing the form (with the select list in question) to another page. But, you are apparenlty having a problem accessing the POSTed value on that page. Assuming you are getting directed to the correct processing page ($editFormAction) then the problem lies in that page. EDIT: By the way, you have some superfulous (sp?) code here $result = mysql_query($sql) or die ($sql . '<br />' . mysql_error); if (!$result) { echo 'Query failed'; exit; } If the query failes the "or die()" satatement will execute. So, the "if (!$result)" could never be run.
-
<?php //Create function to create select list of categories for a movie function categorySelect($movieID, $categories, $selectedCatID=false) { $selectHTML = "<select name=\"category[{$movieID}]\">\n"; foreach($categories as $catID => $catName) { $selected = ($catID===$selectedCatID) ? ' selected="selected"' : ''; $selectHTML .= "<option value=\"{$catID}\"{$selected}>{$catName}</option>\n"; } $selectHTML .= "<select name=\"category[{$movieID}]\">\n"; return $selectHTML; } //Get list of categories and create array for use in above function $query = "SELECT ID, Name from Categories ORDER BY Name"; $result = mysql_query($query); $categoryAry = array(); while($cat = mysql_fetch_assoc($result)) { $categoryAry[$cat['ID']] = $cat['Name']; } //Get list of movies to display $categoryID = (int) $_GET['category_id']; $query = "SELECT ID, Title, CategoryID, URL from Movies WHERE CategoryID = $categoryID"; $result = mysql_query($query); //Create output for the movies $movieOutput = ''; while($movie = mysql_fetch_assoc($result)) { $movieOutput .= " <tr>\n"; $movieOutput .= " <td>{$movie['ID']}</td>\n"; $movieOutput .= " <td>{$movie['Title']}</td>\n"; $movieOutput .= " <td>" . categorySelect($movie['ID'], $categories, CategoryID) . "</td>\n"; $movieOutput .= " <td>{$movie['URL']}</td>\n"; $movieOutput .= " </tr>\n"; } ?> <table> <tr> <th>ID</th> <th>Title</th> <th>Category</th> <th>YRL</th> </tr> <?php echo $movieOutput; ?> </table>
-
The "results" you display are invalid. As I told you in a post just yesterday, your "Category" field in the movie table holds the Category ID - not the name. So, your results would look like this: ID - Title - Category - URL 0 Name 1 www.xyz 1 xyz 1 www.abc Because the field is named "Category" you continue to misinterpret what that field holds. I suggested that you should change the name to CategoryID to avoid the same mistake in the future, and here we are just one day later and you have made the same mistake again. If I (or someone else) was to look at this post and did not know that earlier information, the proposed solution would be entirely different. Before you generate the list of movies from the result you should get a list of the Categories (ID and Name). You can then use that to create the select list next to each movie entry and show the currently selected. Value. Then, when the page is submitted you would use an UPDATE to change the calues for each movie - not an INSERT I'll psot some sample code in a few minutes.
-
First of all, you are talking about re-indexing the array, not reordering. Secondly, an array "should" start with a 0 index not 1. An easy way to re-index an array so the indexes start at 0 and increment sequantially is to use the function array_values(). But array_values() doesn't affect the array used int eh function - it returns an array (that will be numerically indexed). So, to change the original array you need to assign the returned value to the variable you want affected - like so: $array = $array_values($array); EDIT: Looking at what you are trying to do, I would highly recommend you do NOT try to reindex the entire $_SESSION variable as it will affect EVERYTHING in the session variable. Assuming those values above are orders, I would store those then in a sub-array of the $_SESSION variable under $_SESSION['orders'] (or something similar). You could then reindex the orders without affecting anything else storded in the session variable using $_SESSION['orders'] = $array_values($_SESSION['orders']);
-
if(count($myrows)) { $lastDate = false; foreach($myrows as $m) { //Date has changed, change class if($lastDate != $m->signupdate) { $class = ($class=='class1') ? 'class2' : 'class1'; $lastDate = $m->signupdate; } echo '<tr class="{$class}"><td>'.$m->signupdate.'</td><td>'.$m->name.'</td><td>'.$m->notes."</td></tr>\n"; } }
-
Cannot add or update a child row: a foreign key constraint fails.
Psycho replied to shenagsandnags's topic in PHP Coding Help
To follow up on ManiacDan's response: In your movies table you have a field called "Category" - is that supposed to be the category name? That wouldn't make sense. So, I assume the value of that field should be the category ID. But, your code for the select list is using the category name as the value. So, if my assumption is correct that the "category" field in the movies table should be the category ID, my first recommendation would be to rename that field to prevent this type of problem in the future. But, to fix the problem as you have it now, you would just need to change the code that generates the select list so the user "sees" the category name, but the value is the category ID. $query = "SELECT ID, Category FROM categories"; $result = mysql_query($query) OR DIE ("There was an error" .mysql_error()); while($row=mysql_fetch_array($result)) { echo " <option value=\"{$row['ID']}\">{$row['Category']}</option>"; } -
Yeah, but checkboxes without labels are pretty worthless. Plus, since that code is run in a loop you would be duplicating fields with the same name. You need to either give the fields unique names or create them as arrays echo "<input type=\"checkbox\" name=\"choice1[]\" value=\"{$info['Que_Choice1']}\" /> "; echo "{$info['Que_Choice1']} <br />\n"; echo "<input type=\"checkbox\" name=\"choice2[]\" value=\"{$info['Que_Choice2']}\" /> "; echo "{$info['Que_Choice2']} <br />\n"; echo "<input type=\"checkbox\" name=\"choice3[]\" value=\"{$info['Que_Choice3']}\" /> "; echo "{$info['Que_Choice3']} <br />\n"; echo "<input type=\"checkbox\" name=\"choice4[]\" value=\"{$info['Que_Choice4']}\" /> "; echo "{$info['Que_Choice4']} <br />\n";
-
Check the rendered HTML code and validate that there is a validly formatted LINK tag to specify the style sheet. If that tag is there (and properly formatted) then I would guess that either the href path in that tag is incorrect or the linked style sheet does not have the proper code to change the BG image.
-
Regarding the UPDATE process. There is a finite number of "subject_level_id" values that a tutor can be assigned to. AND when an "update" is made you are passing all the "checked" values. You don't directly "know" what values were unchecked that were previously checked. The easiest thing to do in this instance is to DELETE all records for the tutor in the tutor_overall_level_subject table and then run a single INSERT query to add all the checked values. Sample code $tutorID = mysqli_real_escape_string($dbc, trim($_POST['tutor_id'])); //Delete all current records for tutor $query = "DELETE FROM tutor_overall_level_subject WHERE tutor id = $tutorID"; mysqli_query($dbc, $query) or die(mysqli_error($dbc)); //Generate VALUE(s) from POST data for the INSERT query $values = array(); foreach($_POST['subject_level'] as $subjectLevel) { $subjectLevel = (int) $subjectLevel; $values[] = "($tutorID, $subjectLevel)"; } //Create query with all the values to be added $query = "INSERT INTO tutor_overall_level_subject (tutor_id, subject_level_id) VALUES " . implode(', ', $values); mysqli_query($dbc, $query) or die(mysqli_error($dbc)); Note: if you needed to retain the originally checked records (for example you need to retain the date added) you can add just the new records and delete only the removed records. But that would require some additional steps. And, since you are not storing anything such as a date which would require that, this approach of deleting everything and only added the checked values makes more sense.
-
In the loop that processes the records, this function is called each time a change is detected in the $current_level_id . That include the very first record since $current_level_id is first set to false. So, the array passed to the function will have no records. That line is to simply exit the function without returning anything. No, not emptied. I just defined it as an empty string. In the loop I am appending additional text using .=. On the very first instance of that there would be a "notice" exception if $htmlOutput was not already defined because it would be trying to append a value to a variable that doesn't exist. In most PHP environments the notice would be ignored. But, it is just good programming practice. The dynamic part of the code is only generating the table contents. The TABLE tag is in the HTML code that comes after the PHP code. This is standard practice of separating your logic (the PHP dynamic code) from the presentation (the HTML layout). <table> <?php echo $checkboxes; ?> </table> In the loop that processes the data I build an array (called $level_data) of the data associated with each level. Then when I have all the records for a level I pass the variable to the function createLevelCheckboxes(). The function uses the variable $levelArray. I could call that variable anything I want - even use the same variable name of $level_data. But, because of variable scope it is a separate variable within the function. Your terminology is not quite correct. I pass the value of 5 to the function as the second parameter. The second parameter in the function is $columns so it is set to the 2nd value passed. So, you could then change those function calls to dynamically change how many columns of checkboxes will fit in a row. That is to append a value to a string. Example: $foo = "bar"; $foo .= "1"; //Append a value using .= echo $foo; //Output: bar1 $foo = "2"; //Set/replace a value using just = echo $foo; //Output: 2 You are not understanding the modulus operator (%). It's not whether it gives you a remainder - it gives you THE remainder. So, (assuming $columns is 5) the modulus will be 1 on the 1st, 6th, 11th, 16th, etc. records. In other words the remainder will be 1 on ever record that should start a new row. The modulus will be 0 when the modulus ($recordCount / $columns) has no remander (i.e. is perfectly divisable). That will occur on records 5, 10, 15, 20, etc. In other words, on each record that should end a row. I am calling the function using $checkboxes .= createLevelCheckboxes($level_data, 5); So, I am appending the output of the function to the variable that is later used to display the output in the table (at the botton in the HTML code). If I don't "return" the code then nothing will be appended to $checkboxes. I am doing a LEFT JOIN of the tutor_overall_subject_level table. I use a LEFT JOIN because there is not a match for the tutor to every record. The LEFT JOIN ensure all the records from the LEFT table will exist even when there is no record in the right table to join to. The "value" in those instances will be null. So, I know from this query that any record that has a value in the tutor_id field is one where that tutor is associated with that level/subject. For ones where the tutor is not associate the value would be NULL. The IF statement is used to test if the value in that column is the same as the tutor id (as opposed to null). If true the value of that field (checked) in the result set will be 1, else it will be 0. I then use that field in the processing code to determine whether the checkbox should be checked or not. While processing the DB results I add each record to an array. I use $current_level_id as a flag/trigger to determine when the current record is a different level than the last. When that happens I call the functino to generate the output for that level and all the applicable subjects. I then clear the array so the new level records can be added and reset the flag to the current level so when the next level is detected the process can start over. You need to read up on functions. The value you pass to a function can be directly (as I do with the number 5 as the second parameter) or as a variable (as I do with $level_data), or other manners as well. When the values are passed to the function they are used to populate the parameter variables in the function. In this case I used $levelArray to accept the first parameter input. A function has no "knowledge" of variables created outside the function and the name of variables used as parameters has no correlation to any values/variables used to pass data as parameters to the function. THere are some "tricks" you can employ here which are beyond this explanation. I use $level_data to add the records to until the trigger detects that the previous level was complete. It then uses that variable to send the data to the function to generate the output. It is not "declared" again, it is "called" again. The reason is that the LAST level will not trigger the if($current_level_id != $data['level_id']) to generate the output. So, you need to add this call after the loop completes to generate the output for the last level and its subjects. As an example, suppose you only had two levels (level 1 and 2). When the first record is processed the flag $current_level_id is set to 1 and the record is added to the array $level_data. As additional records for level 1 are processed there is no change in the $current_level_id so the records are just added to the $level_data array. Now, whenthe first record for level 2 is processed, the IF statemetn detemines that there is a change in the $current_level_id and the function createLevelCheckboxes() is called to generate the output for the level 1 records. Then the $level_data array is reset to an empty array and the $current_level_id is set to 2. The remainder of the level 2 records are processed and added to the $level_data array. Since the last record will be level 2 there is no change to $current_level_id to trigger the code to generate the output. That is why we need to call createLevelCheckboxes() after all records are processed to generate the output for the LAST level. Here is the code with comments <?php //Process the results $checkboxes = ''; //Create variable for output $current_level_id = false; //Flag to check when records change level // $level_data = array(); //Temp array to hold all the records for a level // Line above is not actually not needed since it is defined in the IF statement below on the first record while($data = mysqli_fetch_array($sql)) //Iterate throug the DB results { if($current_level_id != $data['level_id']) //Determine if this level is different from the last { //This code block is run whenever a change in level is detected to generate the HTML code // for that level and its subjects. //NOTE: This code block will be triggered on the very first record - but // no output will be generated by the createLevelCheckboxes() function since // $level_data will not have any records yet $checkboxes .= createLevelCheckboxes($level_data, 5); //Set the $current_level_id trigger so this code block is not triggered // until the next record with a different level id $current_level_id = $data['level_id']; //Create/reset the $level_data for the new level $level_data = array(); } //Add the current record to the $level_data array $level_data[] = $data; } //Call the createLevelCheckboxes() function to generate the HTML for the LAST level records $checkboxes .= createLevelCheckboxes($level_data, 5); ?>
-
OK, let's see what we can do here. After reviewing your tables I think the db design can be improved on. You have a table of subjects and a table of levels. But. then you also have a table that associates subjects and levels. You then seem to associate tutors with those records in the tutor_subject_level table. Is there a reason for the tutor_subject_level table? Are certain levels only applcable to some subject? If all levels can be applicable to all subjects then I would suggest replacing that table with one to directly associate tutors to subjects and levels. (i.e. tutor_id, subject_id, level_id). Anyway, using the structure you have I think the following might work. I think the problem with the previous query was how I used the WHERE clause. Based upon your code/images I am making the assumption that you want to display all the levels and all the associated subjects for each level on this page (with only the ones associated with the tutor checked). So, I have rewritten this yet again which - assuming there are no syntax errors = should generate the entire page <?php function createLevelCheckboxes($levelArray, $columns) { if(count($levelArray)==0) { return false; } $htmlOutput = ''; //Display level header row $levelID = $levelArray[0]['level_id']; $levelName = $levelArray[0]['level_name']; $htmlOutput .= "<tr>\n"; $htmlOutput .= "<td colspan=\"{$columns}\">"; $htmlOutput .= "<input name=\"level[]\" type=\"checkbox\" id=\"level_{$levelID}\" value=\"{$levelID}\">"; $htmlOutput .= "<span class=\"zone_text_enlarge\"><label for=\"level_{$levelID}\">{$levelName}</label></span>"; $htmlOutput .= "</td>\n"; $htmlOutput .= "</tr>\n"; //Display each subject $recordCount = 0; foreach($levelArray as $data) { //Increment counter $recordCount++; //Start new row if needed if ($recordCount % $columns == 1) { $htmlOutput .= "<tr>\n"; } //Display the record $subjectID = $data['subject_level_id']; $subjectName = $data['subject_name']; $checked = ($data['checked'] == 1) ? ' checked="checked"' : ''; $htmlOutput .= " <td>"; $htmlOutput .= " <input name=\"subject_level[]\" class=\"subject_a\" type=\"checkbox\" {$checked}"; $htmlOutput .= " id=\"subject_level_{$subjectID}\" value=\"{$subjectID}\"/>\n"; $htmlOutput .= " <label for=\"subject_level_{$subjectID}\" class=\"subject_1\">{$subjectName}</label>\n"; $htmlOutput .= "</td>\n"; //Close row if needed if ($recordCount % $columns == 0) { $htmlOutput .= "</tr>\n"; } } //Close last row if needed if ($recordCount % $columns != 0) { $htmlOutput .= "</tr>\n"; } return $htmlOutput; } $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die(mysqli_error($dbc)); //Run query $tutor_id = mysqli_real_escape_string($dbc, $_GET['tutor_id']); $query = "SELECT tl.level_id, tl.level_name, ts.subject_id, ts.subject_name, IF(tosl.tutor_id='{$tutor_id}', 1, 0) as checked FROM tutor_level AS tl INNER JOIN tutor_subject_level AS tsl USING (level_id) INNER JOIN tutor_subject AS ts USING (subject_id) LEFT JOIN tutor_overall_subject_level AS tosl ON tosl.subject_level_id = tsl.subject_level_id AND tosl.tutor_id = '{$tutor_id}' ORDER BY tl.level_id, ts.subject_name"; $sql = mysqli_query($dbc, $query) or die(mysqli_error($dbc)); //Process the results $checkboxes = ''; //Create variable for output $current_level_id = false; $level_data = array(); while($data = mysqli_fetch_array($sql)) { if($current_level_id != $data['level_id']) { $checkboxes .= createLevelCheckboxes($level_data, 5); $current_level_id = $data['level_id']; $level_data = array(); } $level_data[] = $data; } $checkboxes .= createLevelCheckboxes($level_data, 5); ?> <table> <?php echo $checkboxes; ?> </table><br/>
-
That will work too. But in situations where I have a variable that is used for an error/response message and the conditions are such that there will not always be a "value" for that variable, I just set the variable to an empty string somewhere at the top of the page. In this case you could place $message = ''; before the very first IF condition if (isset($_POST['submitted'])) { // Handle the form That way it is always set. Either solution works and both have their advantages and disadvantages based upon the logic of the page.