Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
Registration form validation, enabling submit button on success
Psycho replied to slyte33's topic in PHP Coding Help
You would have to implement AJAX (JavaScript + PHP) in order to do what you want. But, even if you do, you still need to build it so that the username validation will occur after the submit as well, for two reasons: 1) Users may have JS disabled, in which case, the username validation won't take place. 2) Concurrency: Two users can open the registration page and enter the same, unused, username. Since the username doesn't exist neither of them will get a client-side validation error. But, if user 1 then submits the page, that username will get created. User 2 would then submit his page. You MUST always have server-side validation. So, start with implementing just server-side validation of the username when the page is submitted. Then, you can work on adding client-side validation on top of that. But, client-side validation should NEVER take the place of server-side validation. Also, implementing an AJAX solution will require some thought. You don't want to do it on each press of the key since the time to query the server and come back will be longer than the time for the user to press the next key. So, onchange() would seem a good choice. but, what if the user enters the username into the field and the focus is still in the field. The submit button will still be disabled and the user may not know why it is that way. It creates a usability issue. Here is what I wouold do. Implement the form with just server-side validation. Then, add a button called "check username" that the user can click to check the username is not in use before submitting the form. Not exactly automated, but it won't have the issues described above. -
It would have been helpful if you gave an explanation of the data being returned. You should be running your query to return data in this fashion (ordered by status first): player_name | status Player 1 | Status 1 Player 2 | Status 1 Player 3 | Status 2 Player 1 | Status 2 Player 4 | Status 2 Player 5 | Status 3 Player 6 | Status 3 Player 7 | Status 4 Player 8 | Status 4 Then your display code would look something like this $currentStatus = false; //Flag to detect change in status while($player = mysql_fetch_assoc($results)) { if($currentStatus != $player['status']) { //Status has changed, display status header $currentStatus = $player['status']; echo "<div>{$currentStatus}</div>\n"; } //Display player info echo "{$key['playerFirst']} {$key['playerLast']}, {$key['year']}<br>\n"; }
-
This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=343133.0
-
To dynamically change the options in a select list you need JavaScript = not PHP. Moving to the javaScript forum
-
You should never make the functionality of your application rely upon JavaScript. JS should only be added to provide additional functionality on top of something that will work without it. Since you plan to use these field to update records, then you need to give them names as I said before. You should give them the same name as the database field to be consistent. If you want one form to update many records, the solution is simply. Name the fields so that they are arrays with the index of each field the record id. <input type="checkbox" name="fieldname[recordID]" /> If you want a separate form for each record, then just add a hidden field into each for to identify the record id. having said that, here are good reasons NOT to allow updating of all records in one form. Specifically performance and scalability concerns. Depending on the amount of records and the user base those concerns can be mitigated. My personally preference is to give a list of records with a button/link on each record to go to an edit page.
-
Use double quotes to define the string and then you don't need to escape the single quotes in the string. $q2 = "SELECT m.first_name, c.body, c.status, DATE_FORMAT(c.created_on, '%l:%i%p on %b %e, %Y') as date_created FROM member AS m INNER JOIN comment AS c ON m.id = c.member_id WHERE c.article_id=?"; I woudl suggest just trying the query. I don't think the 'on' in the date parameter will cause a problem because it is being treated as a strnig. But, if it does cause a problem, then you could just as easily get the two parts of the date separately. In fact, that is a better approach, since the "on" is really a separate "entity" from the date. If you ever wanted to make the application localized you would have some difficulty in doing so. $q2 = "SELECT m.first_name, c.body, c.status, DATE_FORMAT(c.created_on, '%l:%i%p') as time_created, DATE_FORMAT(c.created_on, '%b %e, %Y') as date_created FROM member AS m INNER JOIN comment AS c ON m.id = c.member_id WHERE c.article_id=?";
-
I typically have one page, but that page will include() the code necessary to either validate and/or display the form Rough example on the "main" page (e.g. 'myform.php') //Var to hold validation error (if form was posted) $errors = array(); if(isset($_POST['someformfield'])) { //Include the file that does the form validation include('form_processing_page.php'); //If any validation errors occur, they will be added to the $errors array //If validation passes the validation page can process/save the data OR call another page to do that logic //But, at the end of processing, user is redirected to a confirmation page using header() followed by exit() //so the remaining code on this page is not executed } //Include the html form page // This only happens if the form was not submitted or if there were validation errors include('form_html.php'); //The html content page will include logic to display the errors if the exist
-
MySQL Database insert validation, and displaying info
Psycho replied to mat3000000's topic in PHP Coding Help
I think mikesta707 misspoke. he meant to say that the content already stored in your database IS already affected. -
MySQL and PHP timestamps are not compatible. A PHP timestamp is a long integer that represent the number of seconds since the epoch (Jan 1, 1970). A MySQL timestamp is in the format "YYYY-MM-DD HH:MM:SS". The PHP date() function expects a PHP timestamp, not a MySQL timestamp. There are various ways to convert from one to the other - either in PHP or MySQL. You can use MySQL's date format as Pikachu suggested, but I'm more comfortable using PHP's date function. And, PHP has a very simple wy of converting a MySQL date/timestamp to a PHP timestamp: strtotime(). echo '<p class="commentDate">' . date('g:ia', strtotime($createdOn)) . ' on ' . date('M j, Y', strtotime($createdOn)) . '</p>';
-
Use mysql_real_escape_string() on any string input being stored in the database. And, you will want to use htmlentities() before displaying to the page - else it could be interpreted as code in the HTML page and either not be rendered, cause display issue, or - worse - cause an XSS attack.
-
The error is pretty self explanatory. The second parameters is expected to be a "long" (i.e. long integer - in this particular case a timestamp). It looks like you have the format string and the timestamp transposed. http://us.php.net/manual/en/function.date.php string date ( string $format [, int $timestamp = time() ] )
-
I can't see what the purpose of those checkboxes are. You aren't even giving them a name so,they can't be used for editing the data. But, let's assume they are only for display. My first recommendation would be to write your code in a manner that is easily readable. Putting all that code into one echo statement is not easily readable and will be just as unreadable in the HTML source created. Another tip[, it is not necessary to have a condition such as if($foo == true) { Just use if($foo) { This is just a rough example based upon what you are currently doing, but I have a feeling if I saw all of your code and had a better idea of what you are trying to accomplish I would probably do something very different. <?php $checkboxFields = array( 'fact-sent', 'fact-payed', 'domain', 'content','design-sent', 'design-approved', 'design-sliced', 'temp-website', 'temp-website-sent', 'temp-website-approved', 'cms', 'seo', 'analytics', 'webmaster-tools', 'website', 'website-online'); while ($row = mysql_fetch_array($result)) { $formHTML = "<td class=\"customer\">{$row['project']}</td>\n"; $formHTML .= "<td class=\"customer\">{$row['customer']}</td>\n"; foreach($checkboxFields as $fieldName) { $checked = ($row[$fieldName]) ? ' checked="checked"' : ''; $formHTML .= "<td class=\"data\"><input type=\"checkbox\"{$checked} /></td>\n"; } // OUTPUT echo "<form name=\"checkbox_form\">\n"; echo "<tr>\n"; echo $formHTML; echo "</tr>\n"; } ?>
-
What do you mean by "I am trying to call variables inside a function". In the code you posted above you are passing two values into the function as two parameters. Then, based upon the value of the first parameter, you are modifying the value of the 2nd parameter. And, that's it. You don't apss anything back from the function. What exactly are you trying to accomplish with his function. It looks like you are using it to determine if a form field is disabled or not, but I'd be interested in seeing how you plan to use it.
-
I'm not using "?" in the query. I think you are referring to my use of the ternary operator. This is sometimes referred to as the shorthand version of if/else. But, it's not quite the same. So, in this example $locationChange = (isset($file_location)) ? ", location='{$file_location}'" : ''; I am setting the value of $locationChange based upon whether the variable $file_location is set. If it is set, then $locationChange will be set to the string: "", location='{$file_location}'"". If it is not set then $locationChange will be an empty string. In a more broad sense it can be visualized like this $variable = ( CONDITION[s] ) ? TRUE_RESULT : FALSE_RESULT ; You can also use it for other purposes echo "Today is a " . ((date('D')=='Sat' || date('D')=='Sun') ? "weekend" : "weekday");
-
Um, well you *should* be updating by an ID and not the username. I assumed 'uname' was really the user ID and you just chose a poor name for that field. But, the reason it is always zero is because you are using '%d' in the sprintf() function. That tells the parser that the value should be an integer. Therefore any string that can't be interpreted as an integer is converted to 0.
-
If you need to utilize values set outside a class within the class, then you should pass those variables into the class - using a setter method. As for "plainly within a class", not 100% sure what you mean, but the values should be "properties" of the class and then you can set the value anywhere in the class using $this->varname
-
This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=342929.0
-
What are you trying to accomplish that requires you to get the pointer position? My guess is there is a more efficient method to do what you want. But, if you really need to know the pointer position (which I really doubt), then build a class to use to replace the mysql_fetch_ functions that will maintain the pointer position as a property in the class.
-
You didn't read what I just said: there is nothing wrong with single or double quotes - but they must be "strait" quotes. I.e. they cannnot be the left/right slanted quotes: These are OK: ' " These are NOT OK: ‘ ’ “ ”
-
Personally, I don't like some of the changes jamesxg1 made. For example, I see no reason to define strings with double quotes and then exit the string to concatenate a variable. The beauty of double quotes strings is that you can have variables int he string that will be interpreted. Anyway, here's my revision and some notes: 1. You were definging $id at the top of the page as $id = $_POST["id"]; But, before you use that value, it gets overwritten when it gets redefined in the foreach() loop. That line should be removed. 2. You are not validating the values of active before using them in a query 3. The values for 'name' should also be trimmed and empty values discarded. No need to implement that before the foreach loop though. 4. You are already updating all the records in a loop, so there is no reason to handle the 'active' values separately. You should handle all your updates in one query, but if you are going to loop over each one do all the updates for each. 5. There is no reason to create two completely different queries based upon whether a file upload is done or not. Simply add logic to modify the one query as needed. 6. There was no validation of the $id as an integer. The following should accomplish the same as you previously had, but is greatly simplified <?php /* This script is for use on the Manage Menu's pages and updates all menu items. */ /*==================================*/ /* DATE BASE CONFIGURATION */ /*==================================*/ include_once "../../config/config.php"; /*==================================*/ /* SET VARIABLES */ /*==================================*/ $menu_file = $_FILES['menu_file']; /*==================================*/ /* Update Menu Names */ /*==================================*/ foreach($menu_name as $id => $menu_name) { //Validate the id as an int if($id != intval($id)) { header("Location: ../../../index.php?page=Menu's"); exit(); } //Validate record name $menu_name = mysql_real_escape_string(trim($menu_name)); if(empty($menu_name)) { header("Location: ../../../index.php?page=Menu's"); exit(); } //Set active value for record $active = (isset($_POST['active'][$id])) ? 1 : 0; //Variables for file upload $file_name = $menu_file["name"]["$id"]; //name of file on users machine $file_type = $menu_file["type"]["$id"]; //type of file being uploaded $file_size = $menu_file["size"]["$id"]; //size of the uploaded file in bytes $file_error = $menu_file["error"]["$id"]; //returned PHP error codes for upload $file_temp = $menu_file["tmp_name"]["$id"]; //temporary name on server //Is a file upload needed? if(isset($file_name)) { //Include handler.php, for file validation and upload include_once "./hanlder.php"; } //Update database //Only include change to location if '$file_location' is set $locationChange = (isset($file_location)) ? ", location='{$file_location}'" : ''; $query = "UPDATE menus SET menu='{$name}', active={$active} {$locationChange} WHERE id='{$id}'"; $query = mysql_query($query) or die(mysql_error()); } header("Location: ../../../index.php?page=Menus&errors=Menu_Change_Success"); ?> Lastly, defining the variables for the file and then calling an include() file is not efficient. You should not call the same include() multiple times since the server has to read that file into memory again and again. Instead, create a function to do the processing of the upload. You could still put that function into an include file, but you would only include it once in the page (before the loop). Also, instead of defining the variables for the file, I would create the function so that you only need to pass the file POST array ($_FILES['menu_file']) and the id to use. Then have that function return either the file location (if the file existed in the POST data and there were no error in the upload) or false. Then in the main script set the value of $file_location to the result of that function call: $file_location = file_upload_function($_FILES['menu_file'], $id); Then change these lines $locationChange = (isset($file_location)) ? ", location='{$file_location}'" : ''; $query = "UPDATE menus SET menu='{$name}', active={$active} {$locationChange} WHERE id='{$id}'"; To this $locationChange = ($file_location!==false) ? ", location='{$file_location}'" : ''; $query = "UPDATE menus SET menu='{$name}', active={$active} {$locationChange} WHERE id='{$id}'";
-
What? That won't work either. That would ensure that there are no duplicates values within any sub-array. The problem as displayed by the OP is that he wants to ensure there are no duplicates (of a particular value) between sub-arrays. array_unique() only works on values within a single dimension. It would work if those sub-arrays are exactly the same, but the OP only wants to exclude those where one value in the sub-array is a duplicate.
-
@xdeamon: Just to be clear, the problem was not because you were using single quotes. Both the strait single quote (') and the strait double quote (") are both perfectly valid for enclosing strings. Those are the characters just to the left of the enter key (on a standard US keyboard). But, in your original code and in the code for the header you had single "left" (or back) and "right" (or forward) quotes. The single left-quote is the character on the top left of your keyboard, just below the ESC key. But, there is no easy way to enter the right quote. But, both of those special types of quotes are commonly automatically entered in word-processing application, such as MS Word. Any application made for writing code will not do this. You are apparently using a program for creating/editing your code that was not meant to do that. Get a good application for writing code and use it. There are many that have great features for making code writing much easier (auto-complete for functions, tips on parameters needed, automatic indentation, etc.)
-
That won't work on values in a sub-array of a mufti-dimensional array. $phones = array(); foreach ($phoneNumberArray as $index => $record) { if(!in_array($record[3], $phones)) { //First record with this phone number. add phone to the list and leave the record $phones[] = $record[3]; } else { //This phone was in a previous record, remove the record unset($phoneNumberArray[$index]); } } print_r($phoneNumberArray);
-
Did you come up with that scenario on your own? Because that is the exact example in the manual as to why you should not cast an unknown fraction as an integer: http://php.net/manual/en/language.types.integer.php See the 2nd warning down on the page. And there is a link in that warning as to the reason for the error: http://www.php.net/manual/en/language.types.float.php#warn.float-precision [Emphasis added]
-
Don't create your queries inside the mysql_query() function. It makes it difficult to debug problems such as this. A couple of things I see: 1) You are setting a value using "mysql_real_escape_string(1)". That is not necessary. You are specifically setting the value as "1". There is no need to use mysql_real_escape_string() on the value. And since I assume it is a numeric field, you wouldn't use mysql_real_escape_string() on the value even if it was user entered. You should instead set the value as an integer. mysql_real_escape_string() is for STRNG data. 2) You are also using $_SESSION['user'] in the WHERE caluse, but I don't see anywhere in that script that you have initiated the session using session_start(). I suspect that is the real problem. The value is empty, thus there were no matching records. Build your query outside the mysql_query() call so you can add some debugging code: $query = sprintf("UPDATE members SET acntStatus='%d' WHERE uname='%d'", 1, $_SESSION['user']); mysql_query($query) or die("Query:<br>$query<br>Error:<br>" . mysql_error()); //Debugging line echo "Query: $query<br>Affected Rows: " . mysql_affected_rows();