Jump to content

DavidAM

Staff Alumni
  • Posts

    1,984
  • Joined

  • Days Won

    10

Everything posted by DavidAM

  1. COM is the "Component Object Module" created by M$ to allow access to Active-X controls in diverse environments. The $conn = new COM (...) statement creates a new connection object. That object is not actually connected to anything. You need to check connect.php for a $con->Connect(...) method call after creating the object. If that is not present, you need to add one. If it is present, check to see if it was successful. If it was, either you closed it somewhere else, or some (significant) error caused the connection to drop. I don't know (remember) the specifics for the connect call, or what the method signature is for checking to see if the connection is open. Hopefully, though, this should point you in the right direction. Since the root of the problem is not the INSERT statement, you are probably looking in the wrong place. In short, verify that you have a connection to the database. Then find out where it is getting closed, and why, and fix that. Then your input statement should work. If you have other database access (i.e. SELECTs) in this same process, and those are succeeding, then you can start there to look for reasons that the connection is closed.
  2. Try using the PHP constant: DIRECTORY_SEPARATOR instead of using "/". The constant contains the appropriate value (forward-slash or back-slash) for the operating system.
  3. Well, it appears I agree. I can't, for the life of me, think of a single scenario where it makes sense. But I remember doing it once, and it made sense then. I posted a similar comment back in January 2011. I just scanned through most of my code base and found 3 cases where I did it, but none of them seemed significant enough to break tradition. I guess the code has been archived. Or maybe I'm just getting old. Did we run the OP off with all this technical mumbo-jumbo?
  4. Is a meaningless statement in this industry. Or perhaps I should say ambiguous. If you take out the call to the login() function ... "it works" -- You see your full page in all its glory with all the database data that is supposed to be there? "it works" -- You see your page without any error messages, but you haven't written the database parts yet so there is no data displayed? If you are getting database data without calling login(), then some other file is connecting to the database. And it must be using different connection parameters since it isn't throwing any errors. If you just haven't written the stuff to retrieve data from the database (which is what I am guessing the "showproducts.php" file will eventually do), then you really do need to get the login() function working. You are right, you want a function in an include file, that you can use on any page-script that needs database access.
  5. Removed the function from where? Used what as an include? I don't understand what you are saying. Is it working now? The error message tells you the file name and line number where the error occurred. The error message you posted specifically said: login.php is the first included file in the index page you showed. Line 4 of "here is where I defined the function" is the mysql_connect() function call. So it looks like the login() function is in the login.php file. Is that true or not? Are you creating a second login function? You can't have two functions with the same name, but that would be a different error message.
  6. You have to ORDER the SELECT by the category (or whatever) and keep track of the category that is being processed. The logic is something like this: $lastCategory = null; while ($row = mysql_fetch_assoc( ... ) ) { // Did the category change? if ( $row['Category'] != $lastCategory) { // Close the previous category if (!empty($lastCategory)) echo '</DIV>'; $lastCategory = $row['Category']; // Start new category echo '<DIV> ...'; } // Output the details echo $row['Whatever']; } // Make sure we close the last category if (! empty($lastCategory)) echo '</DIV>';
  7. It is using the login() function. That error message is coming from that function. The mysql_connect() is failing. Probably the hostname is incorrect. It might be the username or password, but I think the error message is different for those. Is this database server on the same machine as the php script? If so, you can try "localhost". Or ask your host (admin) to see what the connection parameters are supposed to be.
  8. We're only seeing bits of code here, so we have to guess. In your original post, you grabbed the requested page as $ID now you are switching on $page. Where did that come from, and does it contain what you expect? Just before the switch, you might try var_dump($page); to see what is happening with it. @jesirose: Just FYI, the default does not have to be the last entry in a switch. I sometimes put it first; when doing so more clearly documents the purpose of the switch.
  9. Yeah, I was going to say that there is noting wrong with that (first) query. If there are no non-Aggregate columns in the SELECT list, the aggregate runs across the entire result set. With the second query you have a non-Aggregate column so you need a GROUP BY. SELECT nameColumn, SUM(valueColumn) FROM someTable WHERE something = whatever GROUP BY nameColumn;
  10. This is one of the reasons we separate our application logic from the presentation logic. You are in the middle of an HTML Anchor tag HREF attribute and you are putting PARAGRAPH tags inside it (the HREF attribute). // Get map URL $result = mysql_query("SELECT * FROM site_settings") or die(mysql_error()); $row = mysql_fetch_array($result); $mapUrl = $row['mapurl']; # ... // output the link ?> <h1>Location Map</h1> <p class="indent"> <a href="<?php echo $mapUrl;?>" target="_blank" title="Click here for a location map">Click here for a location map</a></p> Disclaimer: I just rearranged the OP's code. I do not recommend "or die()"; but I do recommend testing to see if the query succeeded.
  11. $ic_row is an array of arrays. You are searching for a scaler value; it will never be found. You probably meant to do $ic_row[$c] = mysql_result($ic_result, $c);
  12. When using mysql_connect, the port number (if it is not the standard port, 3306) is appended to the hostname, with mysqli_connect it is a separate parameter. Use mysql_connect('remotesite.com:##', 'user', 'password') or die(mysql_error()); for testing. The error will tell you why the connection failed. I would use the hostname rather than IP address, so if the server is moved, DNS will continue to resolve it. Do not use http since that protocol is specifically for websites. Don't use www. since that sub-domain is probably directed to the webserver. You just use the domain and top-level-domain i.e. remotesite.com. Unless the remote administrator gave you a specific sub-domain to use. If the error says Can't connect or the server can't be reached or refused the connection (or something), then the server may not be listening on the specified port. If the error says something like Access Denied, then either the username is wrong, or the password is wrong, or there is no entry in the users table for that username from test.com. By default, mySql adds users with permission to connect from localhost only. You have to specifically give the user permission to connect from a remote host. And, unless I'm mistaken, the same username can have a different password depending on the origin of the login request. When granting the user permission, I would, again, specify the hostname, rather than IP address, so if the server is moved, DNS will continue to resolve it. I'm pretty sure the remote server has to be configured to allow remote connections as well. If you are doing this on development systems, either modify the /etc/hosts file for hostname resolution, or use the IP addresses -- DNS will not be able to resolve your internal host names.
  13. The code below will sort any array of words in "qwerty" order -- I don't know why anyone would want to, but here it is. <?php /* $CONST_order - we need to access this array in a callback function as a global. So, I gave it a special name to help prevent modifications to the array elsewhere in the application. */ $CONST_order = array('q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'); // Some sample words to be sorted $text = "class top clone house apple blue"; # $text = "classy appleoyou top class to-me home house apple4you"; // Turn the text into an array of words to be sorted $words = explode(' ', $text); print_r($words); // Sort the array based on the $CONST_order sequence usort($words, 'CB_qwertySort'); // Print the results print_r($words); exit; /* CB_qwertySort - This function accepts two words. It returns an integer indicating the "order" of the two words: -1 if $word1 is LESS THAN $word2, 0 if $word1 is EQUAL TO $word2, or +1 if $word1 is GREATER THAN $word2. Note: This function ignores the fact that there may be characters in the words that are not in the sort order. The array_search function will return FALSE, which we treat as zero, so they will sort equivalent to "q". We could easily test for this and sort these "special characters" as less than or greater than any other letter in the sort order. */ function CB_qwertySort($word1, $word2) { /* I know, globals are a no-no. But I know no other way to get the array into this function. We have taken precautions. */ global $CONST_order; $len1 = strlen($word1); $len2 = strlen($word2); $lenMin = min($len1, $len2); /* Check each character position using the length of the shorter of the words. If one word is shorter and all characters up to that length are equal, then the shorter word is LESS THAN the longer one. */ for ($i = 0; $i < $lenMin; ++$i) { $pos1 = array_search(strtolower($word1{$i}), $CONST_order); $pos2 = array_search(strtolower($word2{$i}), $CONST_order); if ($pos1 < $pos2) return -1; elseif ($pos1 > $pos2) return +1; // "+" just to be clear } /* If we get here, the words are the same, or one is shorter and they are the same for the length of the shorter word. The shorter word is considered LESS THAN the longer word */ if ($len1 < $len2) return -1; elseif($len1 > $len2) return +1; // They must be exactly the same return 0; } It's 60 lines, but if you don't count the opening php tag and the blank lines and comments, and you take out the print_r calls and the exit (which is not needed) and ignore the two setup lines at the beginning, it's 17 lines of code (2 lines over my guess) -- Damn I'm good! (I have to say that every now and then, because no one around here ever does). I use the curly-brace operator (that is an operator, right?) to index the words. Note that: $word1{0} === $word1[0]. That is, you can use the array square-brackets to index a string (as if it is an array of characters). I use the curly-brace, because it adds a level of documentation to the code. It makes it clear that $word1 is a string not some array that was passed in. I did use global but the only way I see to avoid it is to make it a class. If anyone has a suggestion, I'd like to hear it. Since the order array is all lower-case, I did the compare in lower-case, so the sort is case-insensitive. If you add the 26 Upper Case letters to the sort order array, and remove the strtolower() function calls, it will be case-sensitive. Other "issues" are documented in the code.
  14. I meant to reply to your other post last night. Is this homework, or an actual application? This can be accomplished with usort and a simple callback function using a for loop and array_search -- 10 or 15 lines of code (I think). When I get home (and done baby-sitting), I'll take another look at it and provide a more detailed answer.
  15. I usually avoid the DELETE and INSERT approach for several reasons, most of which are just personal preference. If I have a group of checkboxes, such as categories, I name them so it produces an array of the category IDs in the POST array: <INPUT type="checkbox" name="chkCategory[]" value="$CategoryID" ... then I use the following approach -- remember, un-checked checkboxes will not be posted: $selectedIDs = $_POST['chkCategory']; # Do the sanitation (make sure they are integers) # Delete any existing entries that are not now selected $query = "DELETE FROM ItemCategories WHERE ItemID = $itemID AND CategoryID NOT IN (" . implode(',', $selectedIDs) . ")"; # Insert any selected entries that are not already there $query = "INSERT INTO ItemCategories (ItemID, CategoryID) SELECT $itemID, CategoryID FROM Categories WHERE CategoryID IN (" . implode(',', $selectedIDs) . ") AND NOT EXISTS (SELECT * FROM ItemCategories WHERE ItemID = $itemID AND CategoryID IN (" . implode(',', $selectedIDs) . ") )"; The subquery is necessary since mySql will not allow you to JOIN to the table you are inserting. Note: You can avoid the subquery if you have a UNIQUE INDEX on (in this case) ItemID,CategoryID by using INSERT IGNORE My reasons for this approach (in no particular order): Avoids unnecessary holes in the AUTO INCREMENT value in the table (if any); Avoids "wasting" AUTO INCREMENT values (if any) so I don't have to worry about running out; Does not fragment the table and indexes as bad as DELETE and INSERT; If I have a CreateTime column (and I usually do), we are not loosing that data; Disclaimer: I'm not 100% sure of that syntax, I'm not at home where I can check my code base. But I think you can see the logic I use.
  16. While that solution will work, I wonder how it will scale. You will be processing a lot of data from the database and in PHP that you don't really need. As the number of entries in the table increases, the process will take longer. What about this: <?php include ("connect.php"); $query = "SELECT MIN(UID), MAX(UID) FROM Users WHERE Type='AD'"; $result = mysql_query($query) or die(mysql_error()); # ADD THIS $row = mysql_fetch_array($result) $min = $row['MIN(UID)']; $max = $row ['MAX(UID)']; $rnd = rand($min, $max); $query = "SELECT UID FROM Users WHERE Type = 'AD' AND UID >= $rnd ORDER BY UID LIMIT 1"; $result = mysql_query($query); $row = mysql_fetch_array($result) $TheRandomID = $row['UID']; # REMOVE THE WHILE (Since we only have/need one row) #while($row = mysql_fetch_array($result)){ echo '<img src="' . $TheRandomID . '.png>" <br />'; #} ?> The second query will fetch the generated random ID or the next greatest UID (of type "AD"). Since we know that MAX(UID) is a valid selection, and rand() will not return anything greater, the query should always return a valid ID. It is one extra trip to the database, but we reduced the overall amount of data being transferred and processed.
  17. Since Name is the PRIMARY KEY on the table, LIMIT 1 is not needed here. There can only ever be one (or zero) rows for that query. First, in development, turn on error reporting. There may be errors occurring that prevent the query from succeeding: # AT THE BEGINNING OF EACH PHP SCRIPT - TURN ON ERROR REPORTING error_reporting(E_ALL); ini_set('display.errors', 1); Check to see if the query is actually working: $result=mysql_query($query); # ADD THE FOLLOWING LINE if (! $result) trigger_error(sprintf("Query Failed: %s <BR>\nWith error: %s", $query, mysql_error()), E_USER_ERROR); $i=mysql_num_rows($result); // Here we are counting how many rows this result gives us. to see if the query failed and what the error message is. mySql errors do not produce PHP errors, so you have to call the mysql_error function to get them. I don't see why that script would fail, if the player name is in the database. You can echo out the query and try running it against the database (in phpmyadmin or the mysql command line), to see what happens. The only other things that stick out in my mind are: Is the Name column case-sensitive and are you providing the argument in the same case? Name is limited to 24 characters, are you providing a longer name? Try using trim on the input, in case there are spaces; You are using $_GET, is the player name in the url, or is this coming from a form that is POSTed? You say you are new to PHP. Three things you need to learn (or unlearn): [*]Always use long tags: <?php short tags lead to all kinds of problems [*]Forget you ever heard of the error suppression operator "@". Suppressing errors does not make a script work, it just hides the problems [*]You only need stripslahses if "magic quotes" is on. Since that option has been deprecated, you should always have it off if you have control. If you don't have control, you can check to see if it is on -- get_magic_quotes_gpc -- before you stripslashes
  18. True. But if you have, let's say, an "admin" folder on your site, and it isn't linked anywhere, on your site, you would think that it is safe from bots. But some blackhats, seeing "admin" in a robots.txt file, may take it as a challenge to attempt to hack your admin section, and you have told them there is a directory by that name as a starting point for their attempt. Of course, in this scenario, there is no reason to list the admin folder in the robots.txt file, since there would never be any links to it anywhere, the robots would never know to look for it. On the other hand, noobs may see the robots.txt as a security measure which it is not and naively list the admin folder.
  19. I sometimes wonder about robots.txt. Sure, the "legit" crawlers will use it, but the "il-legit" crawlers can use it to find out about sections of your site that may not be linked. I'm still on the fence about it in general. It would not surprise me if the major search engines have (or will build) search sites specifically for mobile pages. In which case, you may or may not want them indexed. I think in this case, I would use the same test on the pages of the mobile site as is used on the non-mobile site. Then redirect (301: permanently moved) the user back to the main site if the user agent is not mobile. Just be sure to use the exact same test so you don't create an infinite loop. Most bots, I suspect, either don't bother to set the user-agent, or clone something from one of the major browsers, so a check on the mobile site should get rid of them.
  20. @darkfreaks - the OP is not trying to display the characters, he is trying to get rid of them. @irfandayan - did you try the solution offered in that question you linked ? $_POST = array_map('stripslashes_deep', $_POST); Since other processes are involved, changing the super global may not be the best answer. Check the WP API documentation. Is there a WP function for retrieving the GET, POST, etc data? If they are messing with it by adding slashes, then they should be providing a way to get it without the slashes. You have not posted your code, so I can't offer a definitive solution. But you could just run stripslashes() on the data when you retrieve it $message = stripslashes($_POST['message']); // or better yet $myPOST = stripslashes_deep($_POST); // then ... $message = $myPOST['message']; If you are getting the doubled-up backslashes in the data the first time you retrieve it, then there may be another plug-in that is messing it up. You could disable your plug-in's one by one until the problem goes away. Then look for updates for the one that was causing the problem. The fact is, any "solution" you come up with that will make your script work, could either cause problems for other scripts/plugins in WP or stop working when WP or other plugins are updated or you remove a plugin (which happens to be the one screwing up the data).
  21. You original problem statement was: Now you say: So, before we chase another wild goose down the rabbit hole, how about you tell us what you are doing, what is happening, how that is different from what you expect to happen, and show us the code that is not doing what you expect? We are not mind readers and two lines of code does not give us any kind of context to figure out what is wrong. Or did I read your last post wrong? Are you saying the problem is solved?
  22. As KevinM1 suggested, it depends on what you mean by "dynamic" and on how the navigation is supposed to work. JQuery is Javascript, so you can not depend on it being on. Users can turn it off. If portions of your navigation are only going to be visible "dynamically", then using JS (or JQ) will prevent some users from seeing and using your site. I would use CSS as much as possible and only depend on JS to enhance the experience for those that have it on. Or for things that cannot be done in CSS.
  23. Do you have session_start at the beginning of that script? Have you tried printing the $_SESSION to see what is in it; at the beginning of the script (before assignment) and at the end of the script (after assignment) and on the next page (which also must have session_start at the beginning)?
  24. There are two magic quotes settings: magic quotes gpc - Affects $_GET, $_POST, and $_COOKIE as well as $_FILES magic quotes runtime - Affects File and Database reads When you say "my magic quotes always return FALSE" which one are you looking at? and how did you look? I don't know any other way that the backslashes would get in there unless you have a function somewhere that is escaping the data. If this script is running in some third-party environment, i.e. Wordpress, etc, there may be something going on there. First, check phpinfo to see what value you are running with Then check any .htaccess files that may be involved for any php directives that might be including files or changing settings Then, create a simple php script to test: <?php if (isset($_POST)) { printf('<PRE>%s</PRE>', htmlspecialchars(print_r($_POST, true))); } $txtLine = (isset($_POST['txtLine']) ? $_POST['txtLine'] : ''); $txtArea =(isset($_POST['txtArea']) ? $_POST['txtArea'] : ''); ?> <HTML> <HEAD><TITLE>Test POST</TITLE></HEAD> <BODY> <FORM action="" method="POST"> <INPUT name="txtLine" value="<?php echo $txtLine;?>"><BR> <TEXTAREA name="txtArea"><?php echo htmlspecialchars($txtArea);?></TEXTAREA><BR> <INPUT type="submit" name="submit" value="Submit"> </FORM> </BODY> </HTML> Navigate to this new test page and type something in both text fields. Be sure to include a single-quote and a backslash in one or both of them. Also, hit enter once or twice in the textarea. Then submit the form. You should see the results in the browser. Are there backslashes shown there? Are there backslashes in the fields themselves after you POST? If this simple script produces the correct output (i.e. no backslashes that you did not type yourself), then there is something in your problem script that is escaping the data. You will need to check the script for any processing of the $_POST array. You will need to check any functions that process that array. You will need to check every file that is included by your script to see if any of them are affecting $_POST. You also need to check any auto-prepend-file that is listed in the phpinfo() results. My next step would be to add that printf statement from the code above, early in my script, perhaps followed by a die call. And keep moving the statement up or down in the script until I find out where the backslashes are being inserted. Most likely, if magic-quotes-gpc is indeed off, you will find a call to addslashes, addcslashes, mysql_real_escape_string, or one of the other database escaping functions somewhere in the script or an include file. 2) While I do not recommend this, to remove all of the back-slashes from a string, regardless of the number of them, you need to use a regular expression. I'm not very good with RegExp when back-slashes are involved, but I think it would be $msg = preg_replace('~\\+~', '', $msg);. Warning: If you use this method instead of finding and fixing the cause of the problem, you will be discarding user supplied data. If the user typed a back-slash in the message, you will be deleting it with the above statement.
  25. We may need to see some code. If "magic quotes" is on, you will get a single back-slash before certain special characters. The preferred solution to this is to turn magic quotes off. If you can't turn it off, you need to call stripslashes. function cleanupPost($paInput) { if ( (function_exists('get_magic_quotes_gpc')) and (get_magic_quotes_gpc()) ) return stripslashes($paInput); else return $paInput; } $msgBody = cleanupPost($_POST['message']); You need to test for the existence of the function, because I hear magic quotes will go away completely in the next major release of PHP, and without that test, the code would break when the function no longer exists. If you are seeing multiple back-slashes in the input, it may be because The form was POSTed and your script decided the data was incomplete, so you sent the form again, with the data from the POST. If magic quotes is on, each POST will add the back-slashes, and if you don't stripslashes before sending it back, they will just keep getting added. Or it could be from other processing in your script. If you are using addslashes or mysql_real_escape_string, or any other escaping function to process the mail message, STOP. You do not need to escape the data for a PLAIN-TEXT mail message, and you would use htmlspecialchars for an HTML mail message. If you show the code where you are processing your textarea, we may be able to provide more insight. Right now, we are all just guessing. @lordshoa: Just FYI -- I am not recommending str_replace as a solution here, there may be other things escaped besides the single-quote. However, if it is needed for the \r\n issue, you can do that in a single call using an array: $message = str_replace(array('\r\n', '\r', '\n'), "\n", message); Note the order (inside the array) and the quoting (single vs double) is important in that particular piece of code.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.