Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
Yeah, that file is 1,300+ lines of code! Whoever wrote that should be shot. Sorry, I'd like to help but I'm not going to spend a lot of time trying to review a 1,300+ script that someone with questionable skills wrote. But, I did do a quick search and found that there is nothing in that code to process a "comment" from POST data. The form is POSTing to the page at http://pickthefights.com/smack-reg/ I assume it is a page named index.php or something similar. You could possibly put in a header() redirect to pool.php at the end of that script so it will redirect back to the script above to show the content. Really not sure without understanding all the logic.
-
No. Again, you say that when you refresh the page that the submitted content is displayed. Please post the code that actually displays the content.
-
Well, you have provided absolutely no details of how the content gets displayed currently. You say the submitted content gets displayed if you refresh, but there is nothing in that code that would display any variable content (whether submitted or manually refreshed). The only variable content I see is the session variable and the $idvar, which are both used to populate hidden fields.
-
Yeah, right. You appear to be simply trying to append a value onto the end of a string. That is as simple as can be. First off, will the first query return one or multiple results? You are using $sql['attrb1'], but you don't show where that is defined. Plus, you never stated any of the errors you have gotten - which you would have. phporcaffeine gave you the right syntax to append the string and the variable. If that is not working it is because $sql['attrb1'] is a varchar value that itself needs to be enclosed in quotes or it does not have the value you expect it to. But, as xyph stated you do not need two queries - just one: $query = "SELECT attrb2 fromt table2 where attrb3 IN (SELECT attrb1 from table1)";
-
I just did several google searches for queries related to php functions to find the number of elements in an array. And each one found the exact manual page to the function you need. Heck, I even used your exact text from above "how many elements are in the array" along with PHP and the first result is the answer you need. By the way, do not use global. Instead pass the variable to your function.
-
Variable scope is a simple concept but can be hard to understand at first if you have preconceived ideas that run counter to how it actually operates. Here are a couple of examples that should help function echoValue1() { echo "The value is: " . $a; } function echoValue2($var) { echo "The value is: " . $var; } $a = 'foo'; echoValue1($a); //Output: 'The value is: ' echoValue2($a); //Output: 'The value is: foo'
-
$user = substr($email, 0, strpos($email, '@'));
-
OK, this is VERY rough code, but it should work for what you are trying to achieve. Bid Page <?php session_start(); $con = mysql_connect("localhost", "root", "") or die ("cannot connect"); mysql_select_db("tab_test") or die ("cannot select database"); //Parse input into SQL safe values $updateTreeID = (isset($_POST['treeID'])) ? intval($_POST['treeID']) : false; $bidAmt = (isset($_POST['newBid'])) ? floatval($_POST['newBid']) : false; //If input values were passed via POST, run update query $response = ''; if($updateTreeID && $bidAmt) { $query = "UPDATE Trees SET CurrentPrice = '$bidAmt' WHERE treeID = '$updateTreeID' AND CurrentPrice < '$bidAmt'"; $result = mysql_query($query); if(mysql_affected_rows()) { $response = "You are now the high bidder"; } else { $response = "You have been outbid"; } } //Create and run query to get all records to create bid forms $query = "SELECT treeID, treeName, treePicture, treeGiver, treeDesc, CurrentPrice FROM Trees ORDER BY treeName"; $result=mysql_query($query); //Create bid forms $forms = ''; while($row=mysql_fetch_assoc($result)) { $treeID = $row['treeID']; $price = '$' . number_format($row['CurrentPrice'], 2); $forms .= "<form id=\"bid_{$treeID}\" onsubmit=\"\" action=\"\" method=\"post\">\n"; $forms .= "<table>\n"; $forms .= "<tr><td><img src=\"{$row['treePicture']}\"></td></tr>"; $forms .= "<tr><td><input type=\"text\" name=\"treeID\" id=\"treeID_{$treeID}\" value=\"{$treeID}\" /></td></tr>\n"; $forms .= "<tr><td>Current Price: <span id=\"priceElement_{$treeID}\">{$price}</span></td></tr>\n"; $forms .= "<tr><td>"; $forms .= "New Bid: <input type=\"text\" id=\"newBid_{$treeID}\" name=\"newBid\" \>"; $forms .= "<button type=\"submit\">Bid</button>"; $forms .= "</td></tr>\n"; $forms .= "<tr><td>{$row['treeName']}</td></tr>\n"; $forms .= "<tr><td>{$row['treeGiver']}</td></tr>\n"; $forms .= "<tr><td>{$row['treeDesc']}</td></tr>\n"; $forms .= "</table>\n"; $forms .= "</form>\n"; } mysql_close($con); ?> <html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <head> <script type="text/JavaScript"> TargetDate = "11/18/2011 6:00 PM"; BackColor = "palegreen"; ForeColor = "navy"; CountActive = true; CountStepper = -1; LeadingZero = true; DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."; FinishMessage = "It is finally here!"; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari var xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var prices = xmlhttp.responseText.split('|'); for(i=0; i<prices.length; i++) { price = prices[i].split(':'); document.getElementById('priceElement_'+price[0]).innerHTML = '$'+price[1]; } } } function updatePrices() { xmlhttp.open("GET", "getPrices.php", true); xmlhttp.send(); setTimeout('updatePrices()', 5000); } </script> </head> <body onload="updatePrices()"> Welcome <?php echo $_SESSION['username']; ?>! <br /><br /> <?php echo $response; ?> <br /><br /> <a href="tab_logout.php">Sign Out</a> <table> <tr> <td>Active Trees</td> </tr> </table> <?php echo $forms; ?> </body> </html> getPrices.php page (for the AJAX) <?php $con = mysql_connect("localhost", "root", "") or die ("cannot connect"); mysql_select_db("tab_test") or die ("cannot select database"); $query = "SELECT treeID, CurrentPrice FROM Trees"; $result=mysql_query($query); $outputAry = array(); while($row=mysql_fetch_assoc($result)) { $outputAry[] = "{$row['treeID']}:{$row['CurrentPrice']}"; } $outputStr = implode('|', $outputAry); echo $outputStr; ?>
-
OK, so you are wanting the price (via AJAX) to be updated based upon 'Other" users' bids. It looks like your original code was running the AJAX code when the user submitted their bid. So, what you want is a JavaScript timed event to poll the server every 30 seconds (but you could also update when the user places a bid). You do not want to refresh the page. Plus, do you want to update the prices for ALL the items on the page as other users place bids or do you only want to update the ones for which the current user has placed a bid?
-
We do send an email. But, this is not a website/application where users can register themselves. They are either created through order processing or an administrator for their firm that is already a user. If they don't receive the email it routinely requires a call to customer service - that costs money. If we can implement something that will prevent some of those calls without affecting any legitimate emails it makes business sense. We can (and have) prevented the wrong email addresses from being used due to simple errors. It doesn't prevent "dan" from being entered as "and", but it does catch some. Plus, we do not need to worry about spammers. Only firms who purchase our software can create users. Like I've said before, one solution does not meet the needs of every situation. I wholeheartedly agree with you on sending an email verification link for a normal website application where users sign themselves up. If that happens, we can simply change the service used for validating emails. But, this same discussion can apply to other validations as well. Technically, there is no limit to how many characters (and what characters) can make up a persons name. But, realistically you have to set some limits due to input fields, database limitations, etc. The longest name I could find on records was a little over 200 characters. Does, that mean that every application should support names that long? What if someone comes along with a 300 character name?
-
That explains it - I bet you are really good at more creative things. I believe that there are a specific set of innate skills needed to be really good at 'creative' functions and a completely different set to be really good at 'analytical' functions. Very rarely do I see a person that has both sets of skills. You can become competent in one area without the innate skills, but it takes more work. Again, this is just my opinion. Good luck to you.
-
The function I provided won't throw any errors - that is YOUR responsibility. The function does exactly as I explained. If the date can't be parsed into a date using strtotime() it will return false. Otherwise it will return a data in a common format. I've made a couple of minor modifications: 1. implemented trim on the string 2. Added a simple regex to change a date in the format 2-5-2002 to 2/5/2002 because where there are numbers separated by dashes, strtotime() would interpret it as dd-mm-yyyy instead of mm-dd-yyyy. By changing it to slashes for that particular format it will be interpreted as US users would expect. 3. Added an additional parameter to optionally set the format of the output. Revised function and test code: function isDate($dateStr, $format='Y-m-d') { $dateStr = trim($dateStr); $dateStr = preg_replace("#^(\d{1,2})-(\d{1,2})-(\d{1,4})$#", "$1/$2/$3", $dateStr); $dateTS = strtotime($dateStr); if(!$dateTS) { return false; } return date($format, $dateTS); } //Begin Test code $testDates = array( '02-15-2005', '3/12/2010', 'Jan 15, 1998', '10-OCT-05', '01/01/2011', '2011-12-25', '15-15-15', 'December 23rd 1905', 'Octoburary 12, 2003', '10-9-12', '12-12'); foreach($testDates as $date) { $validDate = isDate($date); if(!$validDate) { echo "{$date} : Not Valid<br>\n"; } else { echo "{$date} : {$validDate}<br>\n"; } } Output of test code: User Input : Validation Output -------------------------------- 02-15-2005 : 2005-02-15 3/12/2010 : 2010-03-12 Jan 15, 1998 : 1998-01-15 10-OCT-05 : 2005-10-10 01/01/2011 : 2011-01-01 2011-12-25 : 2011-12-25 15-15-15 : Not Valid December 23rd 1905 : 1905-12-23 Octoburary 12, 2003 : Not Valid 10-9-12 : 2012-10-09 12-12 : Not Valid That's not to say you should use this, just that it will work if implemented properly (as is the case with any code).
-
I guess we are mostly in agreement, we just have a difference of opinion on one point - the reason for disallowing "valid" emails that do not conform to what is "common". You, are suggesting that the reason for excluding email addresses is due to spam. My position is from the aspect of protecting the user from their own mistakes - especially when it can have significant consequences. As I stated previously, I don't think there is any one size fits all solution. It all depends upon the specific needs of the application. My position is based on real-world experience in working for a company that provides SaaS and desktop applications worldwide to customers who pay thousands, and sometimes millions, of dollars to use. The SaaS applications have a LOT of dependency upon the email addresses used. Users may not get the email to install their client-side software, they may not receive password reset emails, system notifications (that are required for our customers to comply with US federal law) may not get received, etc. etc. One wrong keystroke can end up costing our support and the customer several hours to resolve. So, for *this* particular situation, it makes sense to exclude emails that may be valid but were more than likely mis-keyed. We aren't overly aggressive. We don't exclude based on a white-list of TLDs (but we do require one) and we allow for a wide-range of characters (including the plus symbol). (Well, that's true for the product areas where I am involved where I wrote the requirements. Other product areas did exclude the plus symbol and we've had to get them to react). But, I have yet to hear of one complaint from our customers that they have had their email excluded due to our validation. But, I have had several instances where the validation prevented me from submitting an email address I had accidentally fat-fingered. So, the custom validation we have implemented is doing its job. It is catching emails that the user has mis-typed and it has not, thus far, prevented anyone from submitting a legitimate email address. If a user comes along that actually has, for example, a space in their username, then we will make a change for that. But, even though a space can be in an email address, I have never seen it legitimately used and see no reason to support it when it is probably always a mistake.
-
But the problem I have with that is: That means you have to write your own custom validation which will absolutely 100% fail to match someone's actual valid email address. Writing your own custom validation takes you a lot of time and it can't be correct. I have never seen anyone (amateur or professional) write a proper email validation regex on their own. So if you say "I have a reason not to use filter_var," then from my experience you're also saying "screw people from australia and anyone who uses plus addressing and anyone who's email ends in a number and any number of other categories that I can't think of right now." Calm down and take a deep breath. No one said we shouldn't support people from Australia or plus addresses or any such nonsense. I was merely pinpoint out that even though the range of "possible" valid emails is quite large, the real-world usage is much more limited. I can speak from first hand knowledge that for some usages allowing the "wrong" albeit "valid" email address can be an expensive proposition with respect to customer service, development, QA, etc. You are right that too many applications needlessly restrict valid email addresses, but that doesn't mean filter_var is the holy grail. There are a small percentage of people that are biologically both male and female, but I'm not going to provide uses with two checkboxes to select gender even though that might be a vaild response. I use plus addresses all the time. Are you aware that if you have a gmail account, such as username@gmail.com, you can use any 'plus' address with that username (e.g. username+shopping@gmail.com) and it will all go to the same inbox? You can then use that information in your rules to easily categorize mail messages. It's also a godsend for testing when you need to have unique email addresses.
-
Did you even try the snippet of code I posted? Besides, YOU need to define what a "regular date" looks like. The strtotime() function can "validate" a lot more strings as a date than you could do with regular expressions - well at least without having to create a ton of different regular expressions. As I said, if YOU want to define the specific requirements for what a valid date is then we can help you create the regex needed.
-
Wow, that is a lot of code just to validate a date. Plus, why would you duplicate the error message for every false validation? The way you have all those nested if() statemetns - nothing would ever pass!!! The first two validations check that the value starts with 1 or 2 digits, but then the third validation checks to see if the value starts with alpha characters! No value would pass both those conditions. PHP has a built in function [strtotime()] that can parse string representations into a timestamp. It is by no means foolproof, but it is pretty good. I'd suggest you use strtotime() on the value. If the function returns false, consider the date invalid, else use the generated timestamp to format the date in the format you need (most likely YYYY-MM-DD for the database). function isDate($dateStr) { $dateTS = strtotime($dateStr); if(!$dateTS) { return false; } return date('Y-m-d', $dateTS); } If you need validations that strtotime() does not support, then please post your specific requirements and I'm sure someone can generate the requisite regex patterns.
-
I see you are using AJAX - and there is nothing wrong with that. But, typically you only want JS to enhance the functionality of your page and not be a requirement of it. So, I would suggest making each record it's own form and use a submit button. Then once it works by using pure HTML, then you can implement JavaScript on top of the current code. Youwould do this by using the form's onsubmit trigger to run the javascript and then do a "return false" which would prevent the form from actually submitting. So, if the user doesn't have JS enabled the form will submit normally, if they have JS enabled then the data is processed via AJAX. Having said all that, the problem you are having is expressly due to 1) the fact that you are reusing names of elements and 2) the javascript is referencing the same elements. Here is some of your JS function: function showCurrentPrice(str,str1) { if (str=="") { document.getElementById("priceElement").innerHTML=""; return; } You used the id of 'priceElement' for all of your records - how is the javascript supposed to know which one you are referring to? There can only be one instance of an id on the page. OK, here is a significant rewrite of your code. I put things in a more logical order and tidied up some things. I've tested this and it works - without the AJAX enabled. I have included a comment next to where the opening form tag is defined that shows what you can put in the onsubmit trigger of the form to get the AJAX working. The revised code should also work for the AJAX, but I don't have the getPrice.php page to test <?php session_start(); $con = mysql_connect("localhost", "root", "") or die ("cannot connect"); mysql_select_db("tab_test") or die ("cannot select database"); //Parse input into SQL safe values $updateTreeID = (isset($_POST['treeID'])) ? intval($_POST['treeID']) : false; $bidAmt = (isset($_POST['newBid'])) ? floatval($_POST['newBid']) : false; //If input values were passed via POST, run update query if($updateTreeID && $bidAmt) { $query = "UPDATE Trees SET CurrentPrice ='$bidAmt' WHERE treeID = '$updateTreeID'"; $result = mysql_query($query); } //Create and run query to get all records to create bid forms $query = "SELECT treeID, treeName, treePicture, treeGiver, treeDesc, CurrentPrice FROM Trees ORDER BY treeName"; $result=mysql_query($query); //Create bid forms $forms = ''; while($row=mysql_fetch_assoc($result)) { $treeID = $row['treeID']; $price = '$' . number_format($row['CurrentPrice'], 2); // TO ENABLE AJAX : use onsubmit="submitBid(this); return false;" $forms .= "<form id=\"bid_{$treeID}\" onsubmit=\"\" action=\"\" method=\"post\">\n"; $forms .= "<table>\n"; $forms .= "<tr><td><img src=\"{$row['treePicture']}\"></td></tr>"; $forms .= "<tr><td><input type=\"text\" name=\"treeID\" id=\"treeID_{$treeID}\" value=\"{$treeID}\" /></td></tr>\n"; $forms .= "<tr><td>Current Price: {$price}<div id=\"priceElement_{$treeID}\"></div></td></tr>\n"; $forms .= "<tr><td>"; $forms .= "New Bid: <input type=\"text\" id=\"newBid_{$treeID}\" name=\"newBid\" \>"; $forms .= "<button type=\"submit\">Bid</button>"; $forms .= "</td></tr>\n"; $forms .= "<tr><td>{$row['treeName']}</td></tr>\n"; $forms .= "<tr><td>{$row['treeGiver']}</td></tr>\n"; $forms .= "<tr><td>{$row['treeDesc']}</td></tr>\n"; $forms .= "</table>\n"; $forms .= "</form>\n"; } mysql_close($con); ?> <html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <head> <script type="text/JavaScript"> TargetDate = "11/18/2011 6:00 PM"; BackColor = "palegreen"; ForeColor = "navy"; CountActive = true; CountStepper = -1; LeadingZero = true; DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."; FinishMessage = "It is finally here!"; //function timedRefresh(timeoutPeriod) //{ // setTimeout("location.reload(true);",timeoutPeriod); //} function submitBid(formObj) { var treeID = formObj.id.substr(4); var bidAmt = formObj.elements['newBid_'+treeID].value; var priceDiv = formObj.elements['priceElement_'+treeID]; if (bidAmt=='') { priceDiv.innerHTML = ''; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { priceDiv.innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET", "getPrice.php?q="+bidAmt+"&s="+treeID,true); xmlhttp.send(); } </script> </head> <body> Welcome <?php echo $_SESSION['username']; ?>! <br /><br /><br /> <a href="tab_logout.php">Sign Out</a> <table> <tr> <td>Active Trees</td> </tr> </table> <?php echo $forms; ?> </body> </html>
-
You have two input fields for each record 'treeID' and 'newBid'. But, you give the fields the same name for every record and only one value can be passed for a single 'name' - unless that name is an array. Plus, you are creating individual forms for each record. Do you want the user to only be able to update ONE record at a time or ALL of them? Looking further at your code, it makes no sense why you would make the ID field an editable input. You aren't letting them insert records and if you change the ID it wouldn't do anything.
-
There is no one size fits all solution. It all depends on what the purpose of the email field is and the "cost" of fixing things later. By having lax rules, how many incorrect, but valid, emails would be accepted and what are the "cost" of getting them changed later? The costs can be development costs to add functionality for dealing with these scenarios, customer service costs for someone to assist the user and even costs associated with customer satisfaction. If they place an order and don't get their email because of lax validation will they consider it their fault or something the company "should have known" to resolve. For example, I think it would be much more likely that someone forgets to include the TLD rather than it being a valid email address. I, personally, wouldn't allow them.
-
When you run a query the system provides a resource ID to the results of that query. You need to use one of the mysql_fetch functions or mysql_result() to extract the data from the result set. //Create teh query $query = "SELECT SUM(likes) as totallikes FROM facebook"; //Run the query (and get a resource identifier) $result = mysql_query($query); //Extract the result from the resource $sum_num = mysql_result($result, 0); echo $sum_num; Note: typically you will want to use one of the mysql_fetch variants to cycle through the records returned in a result set. But, for a single value query mysql_result() works well.
-
The code I provided should output a row for each record in the result set whether that is 1 record (1 row), 6 records (6 rows), or 600 records (600 rows). If you would like more help please provide a more detailed description of the problem and your current results.
-
I 100% agree with the statements above, but . . . I also like to implement client-side validation to compliment server-side validation to provide a more interactive experience for the user. Plus, depending on what version of PHP your host is using, filter_var() may not be available (but if that's the case you should probably change hosts). Anyway, here are a JS and PHP function I have used in the past for validating email formats. Again, you should be using the built in email test using filter_var() if it is available to you. JS function validEmail(emailStr) { //Return true/false for valid/invalid email formatTest = /^[\w!#$%&\'*+\-\/=?^`{|}~]+(\.[\w!#$%&\'*+\-\/=?^`{|}~]+)*@[a-z\d]([a-z\d-]{0,62}[a-z\d])?(\.[a-z\d]([a-z\d-]{0,62}[a-z\d])?)*\.[a-z]{2,6}$/i lengthTest = /^(.{1,64})@(.{4,255})$/ return (formatTest.test(emailStr) && lengthTest.test(emailStr)); } PHP: function is_email($email) { $formatTest = '/^[\w!#$%&\'*+\-\/=?^`{|}~]+(\.[\w!#$%&\'*+\-\/=?^`{|}~]+)*@[a-z\d]([a-z\d-]{0,62}[a-z\d])?(\.[a-z\d]([a-z\d-]{0,62}[a-z\d])?)*\.[a-z]{2,6}$/i'; $lengthTest = '/^(.{1,64})@(.{4,255})$/'; return (preg_match($formatTest, $email) && preg_match($lengthTest, $email)); } I have never had a problem with a "legitimate" valid email not being accepted. Here is a full description of the validation. // NOTES: // // Format test // - Username: // - Can contain the following characters: // - Uppercase and lowercase English letters (a-z, A-Z) // - Digits 0 to 9 // - Characters _ ! # $ % & ' * + - / = ? ^ ` { | } ~ // - May contain '.' (periods), but cannot begin or end with a period // and they may not appear in succession (i.e. 2 or more in a row) // - Must be between 1 and 64 characters // - Domain: // - Can contain the following characters: 'a-z', 'A-Z', '0-9', '-' (hyphen), and '.' (period). // - There may be subdomains, separated by a period (.), but the combined domain may not // begin with a period and they not appear in succession (i.e. 2 or more in a row) // - Domain/Subdomain name parts may not begin or end with a hyphen // - Domain/Subdomain name parts must be between 1-64 characters // - TLD accepts: 'a-z' & 'A-Z' (2 to 6 characters) // // Note: the domain and tld parts must be between 4 and 255 characters total // // Length test // - Username: 1 to 64 characters // - Domain: 4 to 255 character
-
No one ever said you should be perfect when learning. But, that was not what you were saying. You made a statement that inferred that it was OK to write sloppy code to get it working and THEN try and make it "pretty". Too many people come to this forum expressly due to following that kind of process - they create simple errors or have "logic" issues because they don't plan what they are doing before they do it. I was only telling you not to use it as an excuse (doesn't matter if you are new or experienced). Good habits don't magically happen, you have to practice them. I'm glad you got your problem resolved.
-
You obviously didn't try the code I posted, did you? Here is the same code with some debugging information added. Use it. If it does not show you where the errors are, then post what it does output. public function get_new_flows($level) { $last_flow_id = $_POST['id']; $query = "SELECT F.flow_id, F.user_id_fk, F.flow, F.time, U.name, U.facebook_id FROM flows F JOIN users U ON F.user_id_fk = U.user_id WHERE F.flow_id > '$last_flow_id' AND F.level = '$level' ORDER BY F.flow_id DESC " $result = mysql_query($query) or die(mysql_error()); //Debugging info echo "Query: $query<br>\n"; echo "Num results: " . mysql_num_rows($result) . "<br>\n"; $data = array(); //Define array while($row = mysql_fetch_array($result)) { $data[] = $row; } return $data; }