Psycho
Moderators-
Posts
12,159 -
Joined
-
Last visited
-
Days Won
130
Everything posted by Psycho
-
No need to do two queries. Just do one query to get the records and check the number of records returned. Also, you are giving multiple divs the exact same ID, you can't do that. Here is a more logical approach <?php include("Config.php"); function createImageHTML($title, $src=false, $idx=false) { $divID = ($idx!==false) ? "carousel_images_{$idx}" : 'carousel_images'; if(!$src) { $src = '../Gallery_Images/Default.jpg'; } $html = "<li>\n"; $html .= " <div id=\"{$divID}\">\n"; $html .= " <a href=\"#\"><img src=\"{$src}\" alt=\"{$title}\" /></a>\n"; $html .= " </div>\n"; $html .= "</li>\n"; return $html; } $User_id = mysql_real_escape_string(trim($_GET['id'])); $query = "SELECT * FROM biggartfp9_gallery_itemst WHERE User_id='$User_id' ORDER BY Date_added DESC LIMIT 10"; $result = mysql_query($query); $images = ''; if(mysql_num_rows($result)<1) { //There were no results, show 'coming soon image' $images = createImageHTML("Artwork Coming Soon"); } else { //There were results, create image links $idx = 0; while($row = mysql_fetch_assoc($result)) { $images .= createImageHTML($rows['Title'], $rows['Picture'], $idx); $idx++; } } mysql_close(); ?> <br /> <div class="content_box"> <div class="content_box_h">Latest Artwork</div> <div class="content_box_carousel"> <div id="slider"> <ul> <?php echo $images; ?> </ul> </div> </div> </div>
-
Yes, you can use ANY kind of comparison in a CASE statement - you just have to be creative. Remember the case value must match the switch value. So, just use the boolean true for the switch value and the comparisons as the case value Example switch(true) { case ($num>50 && $num<150): //action goes here break; case ($num>=150 && $num<300): //action goes here break; }
-
Joining two tables and limiting data from only 1
Psycho replied to plugnz's topic in PHP Coding Help
I don't think Andy's is quite right. That query will group by "category_name" which I believe is a unique field in the category table. So, that grouping wouldn't do anything. Instead, you would want to group by the "img.name_category" field which is not unique in the images table: SELECT ctg.category_id, ctg.category_name, img.image_id FROM cms_categories ctg INNER JOIN cms_images_category img ON ctg.category_name = img.name_category GROUP BY img.name_category -
Typically, one the first javascript error is encountered no other javascript will run - in that same thread. Did you even check the erro messages that were generated? OK, I was going to put some demeaning statement here because you again created the same problem I identified in promblem #3 above. But, I make that mistake as well when working between PHP and JavaScript. You are trying to concatenatin in JavaScript using the PHP method. This alert('Arr length='.arr.length); //DEBUG Should be this alert('Arr length='+arr.length); //DEBUG
-
Errors 1: You create a var called dt, but later try to refer to it as just d 2: You are trying to split the object and not the value arr = fieldObj.value.split('/'); 3: You are trying to concatenate text using the PHP operator '.' and not the JS operator '+' 4. The getFullYear property has a syntax error (should start with lower case 'g') 5. Your usage of toString() is completely wrong. Should be: dt.getFullYear().toString() 6. Why is the function returning the fieldObj when you don't use it? Although I think the function would be a bad solution, here is the fixed version function valDate(fieldObj) { var arr = new Array(); var dt = new Date(); arr = fieldObj.value.split('/'); if (arr.length<3) { fieldObj.value += '/' + dt.getFullYear().toString(); //Append current year } return; } //valDate
-
It has nothing to do with an array of fields. You code is just screwed up. There is NO WAY that code worked for a single field before you tested against an array of fields. There are numerous errors. besides that code will cause more problems than it would solve.
-
along those same lines, you can also leave the processing page as is but just move the validation logic to the form page. Then when validation passes do an include of the processing page. If the validation logic is the same, then just do an include of that page in the appropriate place on the form pages as well. A modular design will save you a ton of time. Here is an example script <?php //Set some needed vars $errorMsg = ''; $name = ''; $email = ''; $age = ''; if(isset($_POST['name'])) { //Form was submitted, process data $name = trim($_POST['name']); $email = trim($_POST['email']); $age = trim($_POST['age']); //Validate data $errors = array(); if(empty($name)) { $errors[] = " - Name is required."; } if(empty($email)) { $errors[] = " - Email is required."; } //Check for errors if(count($errors)>0) { //There were errors, prepare error message $errorMsg = "The following errors occured:<br />"; $errorMsg .= implode("<br />\n", $errors); } else { //There were no errors, include processing page include("processData.php"); exit(); } } ?> <html> <body> <div style="color:red;"> <?php echo $errorMsg; ?> </div> <br /><br /> Enter your data <form name="test" action="" method="post"> <label for="name"><b>Name:</b></label> <input type="text" name="name" id="name" value="<?php echo $name; ?>" /> <br /> <label for="email"><b>Email:</b></label> <input type="text" name="email" id="email" value="<?php echo $email; ?>" /> <br /> <label for="age">Age:</label> <input type="text" name="age" id="age" value="<?php echo $age; ?>" /> <br /> * Required fields are in bold <br /><br /> <button type="submit">Submit</button> </form> </body> </html>
-
I do have a few other related date functions as well. If I had the time I'd probably construct them all into a class. But, I just don't have the time - or the interest.
-
http://www.php.net/manual/en/function.simplexml-load-string.php http://www.php.net/manual/en/function.simplexml-load-file.php
-
1. For your purposes, I would say yes. Unless there is some functional reason for using 1,2,3 I'd just use the values (see exceptions below). 2. This makes sense if you have some functional use for those values. One option could be to use 0 for false (no), 1 for true (yes) and NULL for N/A. you could then use the value directly in your logic without comaprisons to strings. 3. This makes sense if the list is not static (can be added or removed from) or if you want to allow the application to be used for different languages.
-
I forgot, that function only formats the date, but does not ensure it is a valid date (i.e. 5-50-5555 is a valid format). I have a related function to ensure the date is an actual date. //****************************************************************// // FUNCTION: isDate (dateStr) // // // // This function takes a string variable and verifies if it is a // // valid date or not. Dates must be in the format of mm-dd-yyyy // // or mm/dd/yyyy. It checks to make sure the month has the proper // // number of days, based on the month. The function returns true // // if a valid date, false if not. // // // // Day/Month must be 1 or 2 digits, Year must be 2 or 4 digits. // //****************************************************************// function isDate(dateStr) { var datePattern = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/ var matchArray = dateStr.match(datePattern); //Check valid format if (matchArray == null) { return false; } month = matchArray[1]; day = matchArray[3]; year = matchArray[5]; // check month range if (month < 1 || month > 12) { return false; } //Check day range if (day < 1 || day > 31) { return false; } //Check months with 30 days if ((month==4 || month==6 || month==9 || month==11) && day>30) { return false; } //Check Feb days if (month == 2) { var leapYr = (year%4 == 0 && (year%100 != 0 || year%400 == 0)); if (day > 29 || (day>28 && !leapYr)) { return false; } } return true; }
-
Here is a function from my personal library which I think will do as you ask. It takes a text input and attempts to parse it into a valid date. If it can, it returns the full date string in the format you want. Otherwise it returns false. The user can use just about any character as a delimiter (/, -, ., etc.) but will be returned using the separator you specify. See the examples in the description. //****************************************************************// // FUNCTION: fullDate(dateStr, [dateSep], [splitYr]) // // // // Takes a string variable that may be a 'partial' date format // // and converts it to a full format using the dateSep (defualt /) // // character. If only the last two digits of the year are given, // // the century (first 2 digits) will be determined by the splitYr // // value (default 29). Years greater than the splitYr will be set // // to the previous century, others to the current century. // // // // NOTE: The input may use any non alphanumeric character as the // // date separator. // // // // Examples: 1.3.2005 => 01-03-2005 // // 1/3/05 => 01-03-2005 // // 1*3 => 01-03-2005 // // 1+3+55 => 01-03-1955 // //****************************************************************// function fullDate(dateStr, dateSep, splitYr) { var datePattern = /^(\d{1,2})([^\w\s]{1})(\d{1,2})\2?(\d{2}|\d{4})?$/; var matchArray = dateStr.match(datePattern); //Check valid format if (matchArray == null) { return false; } //Set individual components of the date var month = (matchArray[1].length<2)?'0'+matchArray[1]:matchArray[1]; var day = (matchArray[3].length<2)?'0'+matchArray[3]:matchArray[3]; var year = matchArray[4]; //Set default values if not passed var dateSep = (dateSep) ? dateSep : '-'; var splitYr = (splitYr) ? splitYr : 29; //Convert year if empty or only 2 digits if (year.length<4) { var today = new Date(); var thisyear = today.getFullYear(); if (!year) { year = thisyear; } else { //Determine the century var century = Math.floor(thisyear/100); year = (year>splitYr) ? (century-1) + year : century + year; } } return month+dateSep+day+dateSep+year; }
-
Well, if they already have your password you were screwed anyway. You could always have a reset password function that will send a temp passwrd to your email. Of course, that requires that the other user doesn't change that before you get the opportunity. But, all of this is about trying to correct the problem AFTER it occurs. The primary reason for coding for users without JavaScript is not because of "random security curmudgeon" it is to protect against malicious users that want to do harm. I would say the vast majority of the JavaScript I use is for form validation. I would be a fool to rely upon javascript validation alone. However, I believe there are situations where trying to make something work for a non JS user is counter productive - such as UI functionality that is highly dynamic like moving objects on screen. In those situations that functionality might be adding a lot of value to the application. When that happens a business decision needs to be made as to whether it makes sense to try and build a non JS solution or if that functionality can be restricted from some user. In a previous application we required that JS be enabled for the administration tools because we could state that as a requirement to the people buying the application. But, we made the necessary modifications so normal users without JS could use the application because our clients would not want to restrict any possible customers.
-
Well, you can either create all the DIVs on page load OR implement AJAX to load only the slected DIV. Each has it's benefits and drawbacks. Loading them all at once, as you are, may take longer for the page to load initially if you have a LOT of data and if you are not loading them efficiently (more on this below). BUt, performance on changing the displayed DIV will typically be faster for the user. As long as you don't have an extraordinary amount of data I would stick to this method. Loading just one DIV and then using AJAX to load new content will make the page load faster, but performance for changing a DIV will degrade since a server request will be needed each time. This is a good method when there is a LOT of data and trying to load it all into the user's browser would not be effective. Having said all that, you should still ensure you are generating the content for all the DIVs efficiently. You state You should only be running ONE query to get the data for all the DIVs and then use PHP logic to create the DIVs from the single result set. Running multiple queries like that is horribly inefficinet. If you post the code to get the data and create one of the DIVs, I can provide some sample code.
-
Of course, that requires that the user has JS enabled. This is an old problem. Personally I think relying upon the user to "log out" of a web application is a poor implementation. I would follow the functionaity that Messenger used to have before it supported multiple, concurrent logins. That is, when a user attempts to log in again, log them out of the first session. If people are giving out their username/password to others that is their problem. That way if a user moves from machine A to machine B, they will be able to log in without waiting. The session at machine A could provide an alert that "You have been logged out because another user logged in at another machine". If it is due to a security breach, the user could log back in and immediately change their password.
-
No, it won't work how you think. You could use PHP to dynamically write the 45 functions, but that is not necessary either. Instead, you should just build a better JS function. I don't see that the var "thanks" is used, but since it is set to an object with a specific ID, I'm assuming you should have used it in the last line instead of specifying the object directly using "Acrura1.style.display". Anyway, this single function should work assuming the forms and divs are all inthe same format where the div ID is the same as the form, except with a "1" appended function toggle_cars(carType) { var form = document.getElementById(carType); var thanks = document.getElementById(carType+'1'); thanks.style.display= (form.checked) ? 'block': 'none'; return; } Then change the function calles to this onclick="toggle_cars('Acura');"
-
Guidance sought - Clear form field when user begins entering data
Psycho replied to Chezshire's topic in Javascript Help
It does not make them objects. What it does is makes the functions more flexible and useful. And, it makes it much easier to repurpose code. The function name should be appropriate to what it does. For example, if I have a function to check a valid (formatted) email address (e.g. isEmail()), that function should simply return true/false based upon whether the passed value is correctly formatted - nothing more, nothing less. Then you can repurpose that code in other places. Plus, think about this. Currently your code has different functions for validating, empty(), validemail(), vaildZIp(), etc. In each of those functions you have had to implement the same functionality to populate the field with a message. Instead, you should have a single function for populating the message. Because, if you ever wanted to change the behavior when there is an error you would have to change each and every function. Instead, you should simply use those function to do the validatin and return true/false THEN run a common function to perform the actual error handling. Then, if you want to change the error handling you just need to change one function because your validations would stay unchanged. Here is an example based upon your previous functionality, not exatly how I would do it. function showError(fieldObj, errorMsg) { fieldObj.value = errorMsg; return; } function validateForm(formObj) { if(isEmpty(formObj.name)) { showError(formObj.name, "Name is required."); } if(isEmpty(formObj.phone)) { showError(formObj.phone, "Phone is required."); } if(isEmpty(formObj.email)) { showError(formObj.email, "Email is required."); } else if(!validEmail(formObj.email)) { showError(formObj.email, "Email is not a valid format."); } } As you can see, there is a single function for performing the actual error handling. Now let's say you wanted to add functionality to highlight the field. You could simply change that one function function showError(fieldObj, errorMsg) { fieldObj.value = errorMsg; fieldObj.style.backgrounColor = 'yellow'; return; } With your previous code you would have had to change each and every validation function. -
Guidance sought - Clear form field when user begins entering data
Psycho replied to Chezshire's topic in Javascript Help
Ok, here is a very quick and dirty rewrite that should get you pointed in the right direction. This includes some new functions including one (empty()) which overwrites one of your current functions. The checkForm() function is rewritten and only includes some of the validations as an example. I really don't like that your validation functions are used to perform the alerts and populate the error messages. IMO, a validation function should simply return true/false. This will create a more "full-featured" error handling. It will check for all possible errors and give the user a single error message. It will highlight the field in error with a yellow background, and it will remove the yellow background when accessing the field after an error: 1. Modify the init() function to this function init() {//init places focus on the first form element document.myForm.fName.focus(); //Set onfocus event for all form fields to remove error highlight formObj = document.getElementById('myform'); var fieldCount = formObj.elements.length; for(i=0; i<fieldCount; i++) { formObj.elements[i].onfocus = function() { this.style.backgroundColor=''; } } } 2. Give the form an ID for the above function <form action="http://www.newmanic.com/formtest.asp" method="post" name="myForm" id="myform" onsubmit="return checkForm(this);"> 3. Add the following functions to the head of your document function empty(fieldObj) { //Remove leading.trailing spaces fieldObj.value = fieldObj.value.replace(/^\s+|\s+$/g,''); return (fieldObj.value==''); } //Create global variable var errors; function addError(fieldObj, errorMsg) { errors[errors.length] = ' - ' + errorMsg; fieldObj.style.backgroundColor = 'yellow'; } 4. Modify the checkForm() function like so function checkForm(thisForm) { //check form data for valid info errors = new Array(); if(empty(thisForm.lName)) { addError(thisForm.lName, "Please Enter Your LAST NAME"); } if(empty(thisForm.userName)) { addError(thisForm.userName, "Please Enter Your USERNAME"); } if(empty(thisForm.address1)) { addError(thisForm.address1, "Please Enter Your LEGAL ADDRESS"); } if(empty(thisForm.state)) { addError(thisForm.state, "Please select A STATE"); } if(errors.length>0) { //There were errors alertMsg = 'The following errors occured:\n'; alertMsg += errors.join('\n'); alert(alertMsg); return false; } //if all is passed, submit! return true; } I've also attached a complete file of the modified page. Change extension to htm [attachment deleted by admin] -
Calculating the difference between rows in MYSQL using php?
Psycho replied to Mr Chris's topic in PHP Coding Help
You don't state if you are going to be displaying records for multiple orders at one time or only for one order. I will assume multiple. Here is a rough example to show colums for Order ID, impressions, clicks & difference $current_order_id = 0; while($row=mysql_fetch_assoc($result)) { if($current_order_id != $row['order_id']) { //New order, reset count $current_order_id = $row['order_id']; $first_clicks = true; } else { //Same order as last $first_clicks = false; } //Calculate difference (if not first) $click_difference = ($first_clicks) ? '--' : ($row['clicks']-$last_clicks); $last_clicks = $row['clicks']; echo "<tr>\n"; echo "<td>{$row['order_id']}</td>\n"; echo "<td>{$row['impresssions']}</td>\n"; echo "<td>{$row['clicks']}</td>\n"; echo "<td>{$click_difference}</td>\n"; echo "</tr>\n"; } -
Guidance sought - Clear form field when user begins entering data
Psycho replied to Chezshire's topic in Javascript Help
Personally, I would not put the instructions (i.e. 'Please Enter Data Here') into the form field. I would have text in a div next to the field that I could hide/show or just change the background color of the field. But, there is a simple solution: On every field you want to do this (or just on all fields), add an onfocus even that will "select()" the field - which will cause all current data in the field to be selected. I would just implement it to occur all the time, regardless if that message is there or not. Function: function selectField(fieldObj) { fieldObj.select(); } On the form fields: <input type="text" name="something" onfocus="selectField(this);" /> -
Added emphasis on ALL. As I alluded to previously, you can disable varying levels of cookies.
-
$category = $responses[0]['category_name']; That will assign to the variable $category the value for the 'category_name' index in the first index of $responses. You are dealing with a multi-dimensional array Put this after $responses is defined: echo "<pre>"; print_r($responses); echo "<pre>"; It will show you the entire contents of the array showing the multiple dimensions. Maybe it will make more sense to you then.
-
That link is NOT a link to the actual file. It is a link to a page where you can download the file. The backslash at the end indicates that the "JayCalc 0.2.0.exe" is a folder name not a file name. They may also be using modrewrite functionality to reformat the url into parameters - but that is not needed for what you want. First off, put the files into a filder that is NOT web accessible. Then simply build a front end to determine the user's level of access to the files. If the user is allowed, provide them a link to a download page - adding a unique identifier for the file. Example: <a href-"downloadfile.php?fileid=123">Download this file</a> That page should again check the user's permission to the file. Then user server-side code to READ the file and then serve to the user's browser. To see how to do this, just do some searching for force download scripts.
-
Well, first name seems a poor choice to use for a unique identifier. Typically you would use a user ID. Example code: $user_id = $_SESSION['user_id']; $query = "SELECT * FROM `users` WHERE user_id = '$user_id'"; $result = mysql_query($query); $user = mysql_fetch_assoc($result); //.... echo "Hello {$user['first_name']}:<br /><br />\n"; echo "Select from the following links:<br /><br />\n"; echo "<a href="1.php">Link 1</a><br />\n"; echo "<a href="2.php">Link 2</a><br />\n"; echo "<a href="3.php">Link 3</a><br />\n"; //Only display link four for users of level 1 if($user['level']=='1') { echo "<a href="4.php">Link 4</a><br />\n"; }
-
There are varying levels of "allowing" cookies. Each browser is different, but you can typically block third-party cookies and first-party cookies with personal info but still allow session cookies. In IE, you would use the Privacy Tab to set this.