Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
Is it more optimised to split only essential code between files?
Psycho replied to viralplatipuss's topic in PHP Coding Help
I agree with that. The performance benefits you would gain/lose here are negligible if we're not talking huge amounts of data. So, do what makes logic sense for the overall structure and maintainability. Although , in your example above if you have ~100 arrays all with the same indexes it seems that storing the values in a database would make more sense. -
php mysql time funtion??? datetime??
Psycho replied to YoungNate_Black_coder's topic in PHP Coding Help
I already showed the logic to determine if the snake is pregnant or not, just move that logic to the WHERE clause instead of creating a value. Heck you could have simply used that variable in the WHERE clause. SELECT *, FROM table WHERE sex = 'female' AND ADDTIME(`pregnancy_start`, '00:20:00') > NOW() OR SELECT *, IF(ADDTIME(`pregnancy_start`, '00:20:00') > NOW(), 1, 0) as `pregnant` FROM table WHERE sex = 'female' AND `pregnant` = 1 -
Well, the second comment is // managed by puppet - hostingcms02 Is that your hosting company? If so, contact them about this. In fact, you should contact them anyway.
-
There are a multitude of reasons why an email may find its way into the spam folder. It can be difficult to impossible to actually determine the cause. Here are some things to consider. What email server are you using to send the email? If it is a gmail address and you are not sending the email through gmail's servers it could be targeted as spam. Sort of like receiving a letter where the return address is yours but you know you didn't send it to yourself. Is the email server that is sending the email the "approved" server for the domain used as the from address? Similar to the above. Some email servers - when receiving email - will check the domain of the from email address and then do a reverse-lookup on the originating server to see if it is the authoritative email server for the domain. This prevents spammers from sending email trying to impersonate an official email address: e.g. support@yourbank.com There are lots of additional headers you can set in the email that can help prevent email from being identified as spam. I'm not real familiar with them off hand, but you could do some googling on the subject.
-
php mysql time funtion??? datetime??
Psycho replied to YoungNate_Black_coder's topic in PHP Coding Help
You don't need to add 20 minutes and store that value in the INSERT query. As I explained previously, when you need to determine if "pregnant" is true or false you would run a query such as SELECT *, IF(ADDTIME(`pregnancy_start`, '00:20:00') > NOW(), 1, 0) as `pregnant` FROM table WHERE id = '$id' -
I have no idea what you are trying to do, but I'm pretty sure you are going about it the wrong way. You are putting PHP code into a variable for what purpose? Anyway, the problem is that you are escaping the "n" in the creation of that variable. But, you need the "n" escaped in the code that is eventually created. But, your results don't make sense to me. You are using the heredoc method of creating the string and the escape codes should be interpreted. Therefore, I would expect that the result of $stringData2 would include a literal linefeed (i.e. line break) so your code when written to a page would look something like $message = "First Name: $name_first Last Name: $name_last Phone: $phone Email: $email"; It doesn't make sense to me that you would get an "n" character. But, to get the "\n" to be in the resulting variable you would need to escape the backslash by using "\\n". Then the variable is created with "\n".
-
What errors do you get? You should always have error handling in your code to provide error messages when authentication fails. Based upon the error you should know the area of the failure if not the exact failure. You haven't provided any details of what errors were encountered so trying to debug your code is just a shot in the dark.
-
How to read pdf,word,txt files and display the content in webpage
Psycho replied to sherillnancy's topic in PHP Coding Help
Well, a txt file is easily readable. But then your problem is how is that conversion going to be done and who is going to do it. Just as before there are tools that can do that extract the text from Word/PDF docs, but it will still likely require review and tweaking by a human. -
How to read pdf,word,txt files and display the content in webpage
Psycho replied to sherillnancy's topic in PHP Coding Help
The PHP file system functions are not going to solve this problem. Simply reading the contents of the file source is only going to provide a solution for txt documents. The format of the content in a PDF or Word document can be very complex and nearly impossible to extract in a meaningful way. The reason is you have no way to decipher what is what within the document. There will be different styles/formats on how elements are related. For example, did the user format Positions/Companies/Responsibilities using different header formats or was it formatted using a table layout? Trying to build your own parsing engine will require an intimate understanding of all the possible constructs used in those different formats. It would take you week (more likely months) to get the knowledge needed to even start. But, even then, you would still have a problem restructuring the content into a meaningful way. As I see it, you have three options: 1. Find third party scripts/utilities to read those document types for you. The good ones will cost you money and may require additional software to be installed on the server (which would require you to have a dedicated server, i.e. more $$$). If they are good, they will be able to reformat the content into an HTML format. 2. Have the user enter their Resume into a text-area. Many on-line recruiting sites require this. You could even try using one of the plug-ins that allow the user to submit formatted text (such as this site uses when you go to the "preview" page. 3. Allow the user to upload a document, but don't parse it, just include a link where the user needs to access the resumes. -
Whenever a query does not do as you expect - echo it to the page to validate it contains what you think it does. I would advise NEVER actually building your query inside the mysql_query() function. Instead build it as a string variable so you can see what it contains. You say the variables have been verified, but since you don't show the code of how you verified them I can't take your word for it. Also, although an array variable such as "$_POST[formName]" will work; it is wrong. That is not my opinion, that is stated in the PHP manual several times. Always enclose string keys in quotes. Building upon jcbones's code and adding more error handling and debugging code. This will show if there are any errors and what the results of the query are. If this still doesn't show any affected rows, then there is no record matching the ID given. Make sure you are running against the right database. it wouldn't be the first time someone updated a page in one environment and was testing against a different one. error_reporting(E_ALL); ini_set('display_errors','On'); //Escape/prepare values for query $fnameValue = mysql_real_escape_string(trim($_POST['formName'])); $id =intval($rec); //Create query $query = "UPDATE contacts SET fname='{$fnameValue}' WHERE ID={$id}"; //Debugging line: echo query echo "Query : $query<br>\n";; //Run query mysql_query($query) or die(mysql_error()); //Debugging line: echo line affected echo "Records updated: " . mysql_affected_rows(); Assuming there is an array index of "formid" that would not be the problem. It is wrong - but it will work, which is why it is a "Notice" and not an error.
-
To allow unlimited leagues just change the validation to if($user['league_count']>=$MAX_LEAGUES && $MAX_LEAGUES!=0) Then you can allow unlimited leagues by setting the $MAX_LEAGUES variable to 0.
-
You aren't understanding what he said. Regardless of whether your variable names make sense, you are using the wrong variables that you create. $smart was the value created within the foreach() loop to create the $as variable that IS a query. But, then you used $smart when trying to execute the query. $smart would only contain the last value in the array. But, had you used proper naming for your variables you would have seen that error.
-
Your query is obviously incorrect. When you have these types of errors, echo the query to the page so you can see what was created. I really can't see why you would get that error, there are problems with your code that generates the $as value for a query - but I don't see where you ever run that query! But, I have to assume you are running it somewhere, so here are the problems I see First, you are defining the table as FROM users.users WHERE That is a field - not a table. Second, the if/else within the loop do not have curly braces {} and the execution lines do not immediately follow the if/else. Besides there is a much better way to do that. What I don't understand is what yu are trying to accomplish in that loop. Based upon what you have you want to see if the user tag EXACTLY matches the first value or if the user tag is LIKE the remaining values. Don't you want that to be a LIKE for all of the values? Plus, your logic is wrong - you should be using the $smart variable inside that loop. The code you have will create a WHERE condition multiple times using the complete value sent in the $_GET['s'] variable. Additionally, I don't think you can have spaces in a GET value sent in the query string - they will be converted to %20. You would need to use urldecode() on the value first. Here is an example //Connect to the database before processing the input $terms = explode(' ', urldecode($_GET['s'])); //Convert array values for MySQL WHERE conditions foreach($terms as $key => $value) { if($value =='') { unset($terms[$key]); } else { $value = mysql_real_escape_string($value); $terms[$key] => "users.tags LIKE '%{$value}'"; } //Create the array $as = "SELECT users.username, users.fname, users.lname, users.tags FROM users.users WHERE " . implode(" OR ", $terms);
-
php mysql time funtion??? datetime??
Psycho replied to YoungNate_Black_coder's topic in PHP Coding Help
varchar? That's just silly. Doing that you now lose all ability to use any of the date functions in MySQL. PHP has the date() function that allows you to format a timestamp in any format you wish. Since you need time information in addition to date information, I would use the MySQL timestamp field type. But, it is not the same as a PHP timestamp so you will need to do a conversion between the two. You can either do the conversion in PHP or MySQL (here is a good article on handling dates between PHP and MySQL. Has some useful information: http://www.richardlord.net/blog/dates-in-php-and-mysql). However, if you don't need to actually use the date for display purposes may be able to do everything in MySQL and not need to worry about the conversion. That assumes that when the user submits the form that you want the current date/time entered and it is not a user specified date/time entered on the form. Step 1: Insert or Update a record, setting the start date/time of the pregnancy to "now" INSERT INTO sameTabel (`id`, `startPregnancy`) VALUES ($idValue, NOW()) If you need to set the pregnancy start date/time to something other than "NOW()" (i.e. user specified) then just take the date in PHP and format it using the PHP date() function to MySQL format: "YYYY-MM-DD HH:MM:SS". $mysqlDateTime = date("Y-m-d H:i:s", strtotime($sameDateValue)); Then just use a query similar to what I showed above to determine whether a record is currently pregnant or not. Now, if you want to present the date from MySQL onto the page in the format "jan, 9 , 2011", just get the value from mysql and convert it using date() echo date("M. j, Y", $dateValueFrom MySQL); -
php mysql time funtion??? datetime??
Psycho replied to YoungNate_Black_coder's topic in PHP Coding Help
You are making this more difficult than it needs to be. You shouldn't need to set a value, then at some set time in the future change it back. That would require you to have some automated process constantly running. You simply do that logic in your code. Here is a rough example of what I am talking about. When the form is submitted enter a timestamp into the database for the start of the event (i.e. pregnancy). You want the gestation period to be 20 minutes, so you simply do a query on that field and determine if 20 minutes have passed from that timestamp or not. If no, then the result is pregnant. If yes, then the result is "not pregnant". You never need to update the value. You can do the calculation in PHP or in MySQL. Here is an example of how you could return a Boolean value from a MySQL query to determine pregnant/not pregnant using just the pregnancy start time. Not 100% sure of the sysntax, but it should be anough to get you started SELECT *, IF(ADDTIME(`pregnancy_start`, '00:20:00') > NOW(), 1, 0) as `pregnant` FROM table WHERE id = '$id' -
I forgot to add, the you should use mysql_real_escape_string() on the id value coming from the URL. Otherwise you are open to SQL Injection - potentially compromising your entire database. Use this: $id = mysql_real_escape_string(trim($_GET['id']));
-
After reviewing the last code, I see that not only would separating the selected leagues into their own table would be a more proper structure, it would simplify the code. Revised code is below. You would need to create a new table, called `user_leagues`, with two columns: `userid` and `privateleagueid`. You could then remove the three league id columns from the login table. Of course you would need to update any other code that pulls user/league information accordingly. But, the benefit is that you can easily change the number of leagues a user can select by changing the value of the $MAX_LEAGUES variable and everything else takes care of itself. NO recoding for all those if/else statements. (Note: there was a couple of errors in the code I provided previously that are corrected below as well. 1) I used mysql_affected_rows() as an error check after the first query and it should have been mysql_num_rows(). 2) I put the results for the first query into the variable $user, but then referenced it using $row) <?php //Config var to set max number of leagues for a user $MAX_LEAGUES = 3; //Parse user input $privateleaguename = mysql_real_escape_string(trim($_POST['privateleaguename'])); $privateleaguepasscode = mysql_real_escape_string(trim($_POST['privateleaguepasscode'])); //Get count of currently selected leagues for user $query = "SELECT COUNT(`privateleagueid`) as `league_count` FROM `user_leagues` WHERE `userid` = '{$_SESSION['userid']}' GROUP BY `userid`" $result = mysql_query($query); if(!$result) { echo "Error running query " . mysql_error(); } elseif(mysql_num_rows($result)==0) { echo "Error: User ID incorrect"; } else { //Got user record - proceed $user = mysql_fetch_assoc($result); //Detemine the current count of selected leagues $updateField = false; if($user['league_count']>=$MAX_LEAGUES) { echo "Error: You have already reached the max league count of {$MAX_LEAGUES}."; } else { //Perform the update $query = "INSERT INTO `user_leagues` (`userid`, `privateleagueid`) SELECT '{$_SESSION['userid']}', privateleagueid FROM `privateleague` WHERE `privateleaguename` = '$privateleaguename' AND `privateleaguepasscode` = '$privateleaguepasscode'"; $result = mysql_query($query); //Check results if(!$result) { echo "Error running query " . mysql_error(); } elseif(mysql_affected_rows()==0) { echo "No match for Private League Name and Passcode."; } else { echo "Update successful."; } } } ?>
-
Then you should really consider creating an associative table to store the selected league's for each user. You could, potentially, allow users to sign up to an unlimited number of leagues. Or, if you thought that three leagues is enough you could enforce that as well, but if you then decided to increase it in the future you could easily change it without having to rewrite any code. Besides, it isn't good format storing those three values in there separate columns in the login table.
-
Seriously? Why would you hold back on that requirement? I enjoy helping people, but it is disheartening when you build a solution based upon the requirements submitted only to have the OP then change the requirements. Your question doesn't event apply By the time the if() statement is run, the update has already been performed. All that logic could be stuffed into a single query, but it would be overcomplicated, so the solution is two queries with some logic in-between them //Parse user input $privateleaguename = mysql_real_escape_string(trim($_POST['privateleaguename'])); $privateleaguepasscode = mysql_real_escape_string(trim($_POST['privateleaguepasscode'])); //Check current values in login table for user $query = "SELECT `privateleagueid`, `privateleagueid1`, `privateleagueid2` FROM `login` WHERE `userid` = '{$_SESSION['userid']}'" $result = mysql_query($query); if(!$result) { echo "Error running query " . mysql_error(); } elseif(mysql_affected_rows()==0) { echo "Error: User ID incorrect"; } else { //Got user record - proceed $user = mysql_fetch_assoc($result); //Detemine the field to update $updateField = false; if($row['privateleagueid']=='0') { $updateField = 'privateleagueid'; } elseif($row['privateleagueid1']=='0') { $updateField = 'privateleagueid1'; } elseif($row['privateleagueid2']=='0') { $updateField = 'privateleagueid2'; } if(!$updateField) { echo "Error: User private league id fields are already set"; } else { //Perform the update $query = "UPDATE `login` SET `{$updateField}` = (SELECT privateleagueid FROM privateleague WHERE privateleaguename = '$privateleaguename' AND privateleaguepasscode = '$privateleaguepasscode') WHERE userid = '{$_SESSION['userid']}'" $result = mysql_query($query); //Check results if(!$result) { echo "Error running query " . mysql_error(); } elseif(mysql_affected_rows()==0) { echo "Private League Name or Passcode incorrect"; } else { echo "Update successful."; } } }
-
You've posted code, but neither stated what you expect that code to do or what it is currently doing wrong. Are you getting errors, a blank page, what? Did you even check the HTML source code to verify that the links were being created with the right values? The only thing I see wrong is that you have two WHERE statements in your query. You would have caught that if you added error handling to your code.. Here is a rewrite of your code above with some debugging and error handling added. $query = "SELECT `id`, `img` FROM `gallery` WHERE `remove`=0 AND `category`=1 ORDER BY `order` DESC"; $result = mysql_query($query); if(!$result) { echo "Error running query: {$query}<br>\n"; echo "Error: " . mysql_error(); } elseif(mysql_num_rows($result)==0) { echo "No images found.<br>\n"; } else { while($row = mysql_fetch_assoc($results)) { ##DEBUG ONLY LINE echo " [id={$result['id']}]:"; echo "<a href= 'postImg.php?id={$row['id']}' target='main'><img src='assets/thumbs/{$row['img']}' class='th' /></a>\n"; } require("connect.php"); $id = $_GET["id"]; ##DEBUG ONLYLINE echo "GET['id'] = {$id}<br>"; $query = "SELECT `img`, `caption` FROM `gallery` WHERE `id`={$id}"; $result = mysql_query ($query); if(!$result) { echo "Error running query: {$query}<br>\n"; echo "Error: " . mysql_error(); } elseif(mysql_num_rows($result)==0) { echo "No image found.<br>\n"; } else { $row = mysql_fetch_assoc($result); echo "<div class= 'img' align= 'center'> <img src='../assets/{$row['img']}'><br/><p>{$row['caption']}</p></div>\n"; }
-
I have a suspicion that you are really trying to do this the wrong way. Are you storing the value of "1,2,3" as a value into the database? Besides, if there are 7 possible values, just include 7 checkboxes for input (named as an array). That would make a much more elegant solution. Then just implode the POST values Form: Level 1 <input type="checkbox" name="levels[]" value="1' /> Level 2 <input type="checkbox" name="levels[]" value="2' /> Level 3 <input type="checkbox" name="levels[]" value="3' /> ...etc. PHP $levels = implode(','$_POST['levels']); however, here is a solution for you. The one thing it does not do is prevent a user from entering the same value twice (as long as the value is between 1-7), but it does ensure it matches the pattern you specified and does not contain more than seven digits. function checkLevels($levelsString) { return (preg_match("#^[1-7]{1}(,[1-7]{1}){0,6}$#", $levelsString)!==0); } //Testing array $testvalues = array( "1", "1,2", "11,3,4", "1,2,,4", "1,2,", "1,2,3,4,5,6,7", "", "1,2,3,8", "1,2,3,4,5,6,7,7" ); //Test process foreach($testvalues as $value) { $response = (checkLevels($value)) ? 'Pass' : 'Fail'; echo "[{$value}]: {$response}<br>\n"; } Test results [1]: Pass [1,2]: Pass [11,3,4]: Fail [1,2,,4]: Fail [1,2,]: Fail [1,2,3,4,5,6,7]: Pass []: Fail [1,2,3,8]: Fail [1,2,3,4,5,6,7,7]: Fail
-
Which is better to use echo 'Hello world' or echo "Hello world" ?
Psycho replied to colap's topic in PHP Coding Help
The OPs question was about which is "better" to use - not the most "efficient". Saving milliseconds on a script does not outweigh the possible benefits of using a different method. My preferences are ones which I feel give me the most flexibility and allow me to have a consistent coding style. I agree with Permiso, but I will qualify that. When doing the actual echo I too am doing it within the presentation layer (i.e. the HTML output). But, at that point I am usually only echoing variables I built within the logic of the page (i.e. the core PHP code). When building the variables for output I typically use double quoted strings because of the ability to include variables and escaped characters (e.g. linefeed, carriage return, tab stops, etc.). Also, I almost always enclose my variables within curly braces, as teynon showed, to have a consistent coding style - and I also think it makes the code more readable. If you don't, you end up not including them when you need them and spend too much time trying to debug the error. A consistent coding style and a style which is easy to interpret will help prevent simple errors and make edits/updates much easier. If a program meets it's intended purpose it is not wrong, but there are certainly instances where a particular implementation is a piece of cr*p. In the case of use single quotes or double quotes (or the heredoc or nowdoc methods), neither method has any significant benefits outside of the benefits that you get out of it. By that I mean pick a style that makes sense to you that you can be consistent with. It wouldn't hurt to read the manual on the four different methods of string syntax. There's some really good information in there: http://php.net/manual/en/language.types.string.php -
1. You are not enclosing the values in quote marks 2. You only need ONE query. 3. You need to be validating the user input to prevent errors and SQL Injection //Parse user input $privateleaguename = mysql_real_escape_string(trim($_POST['privateleaguename'])); $privateleaguepasscode = mysql_real_escape_string(trim($_POST['privateleaguepasscode'])); //Create/run single query $query = "UPDATE `login` SET `privateleagueid` = (SELECT privateleagueid FROM privateleague WHERE privateleaguename = '$privateleaguename' AND privateleaguepasscode = '$privateleaguepasscode') WHERE userid = '{$_SESSION['userid']}'" $result = mysql_query($query); //Check results if(!$result) { echo "Error running query " . mysql_error(); } elseif(mysql_affected_rows()==0) { echo "Private League Name or Passcode incorrect"; } else { echo "Update successful."; }
-
EDIT: Your code makes no sense. You do a foreach loop on $questions to create a $question variable, but then you do a foreach loop on $row_data. Where does $row_data come from? Well, wherever it comes from you would do something like this $chart_data = array(); foreach ($row_data as $key => $value) { $chart_data[$value[0]] = $value[1]; }