Jump to content

HenryCan

Members
  • Posts

    48
  • Joined

  • Last visited

Everything posted by HenryCan

  1. I'm finishing up my first few php programs. They are getting input from a user via an HTML form, validating that data at both the client and server sides, and then inserting the data from the form into a MySQL table. It's actually working pretty well in most respects but I'm having a bit of a problem with apostrophes, otherwise known as single quotes. The forms can ask for a title of a book or film and when those titles contain apostrophes, such as Ender's Game or Logan's Run, the insert statement to the database breaks. I believe the apostrophe gets misinterpreted in the Insert statement as closing the apostrophe that preceeds the variable name. Therefore, if the title is Ender's Game, the '$title' gets messed up by having a single quote in the middle of the title. This is the actual insert statement from my code: $insert = "INSERT INTO TopicProposals_Themes (Date_Proposed, Proposer, Title, Discuss, Prepare, Comments) VALUES ('$date_proposed', '$proposer', '$title', '$discuss', '$prepare', '$comments')"; $result = mysql_query($insert, $con); if (!$result) { throw new Exception('Insert of Topic Proposal (Theme) into table failed. Please contact the webmaster. Error number: ' . mysql_errno($con) . '. Error message: ' . mysql_error($con)); } So, what is the correct remedy for this situation? Should I simply change the apostrophes in the insert statement to be quotes ("") instead of (')? Or am I right in suspecting that I need to encode the values when I read them from the form, converting the apostrophes to &apost; and then write the encoded version to the database? I've never had much to do with encoding and decoding and I'm still not clear on the difference between apostrophes and quotes in php so forgive my ignorance in knowing what the right solution is.
  2. I'm trying to write a little PHP program to send an announcement to a low-volume newsgroup once or twice a month to notify people about meetings of my bookclub. I googled and found a couple of articles describing the techniques. Here they are: 1. http://docstore.mik.ua/orelly/webprog/pcook/ch17_05.htm - this one describes the code for a news server that doesn't require a login 2. http://www.joe0.com/2010/12/11/using-php-and-nntp-to-post-new-message-to-usenet/ - this one describes the code for a news server that DOES require a login I have access to my target newsgroup via both types of news servers and I've tried the code given in both the examples after substituting the appropriate values but neither one works. I can access the newsgroups perfectly well in my newsreaders so I know the settings I'm using are correct. But php's fsockopen keeps getting error 110, which is apparently a connection timeout. How do I get around this? I'm guessing that I have to adjust a setting in my router or in Windows to enable the connection. I'm running Windows XP (SP3). I'm not including my code because it is just what you see in the examples I've cited; I'm quite sure I haven't made any typos in providing my newsgroup name, etc. but if you absolutely must see my code anyway, just say so and I'll provide it.
  3. Okay, this was apparently too big a question, i..e. too many aspects to it. I figured out the answer to the first question on my own: my cross-checks used = instead of ==; as soon as I caught that, they started working correctly. I'll ask questions two and three in another post unless I just go straight to a framework like JQUERY or AJAX. I got an answer to the fourth question - use JQUERY or something equivalent - on another forum. I'll ask the fifth question in another post.
  4. I'm not sure what JQuery is or even what you mean by a library in this context. How would the coding change if I was sticking strictly to Javascript and PHP? I'm using a hosting server, not my own server, and I don't think they'll let me install something like JQuery....
  5. I'm writing code to validate a form and I'd like to be able to set the position of the cursor to the field of my choice when I detect an error. I'm getting the strong impression that I have to use Javascript to set the position of the cursor via the focus() function. But how do I pass information from my PHP code to Javascript to tell it which field I want the focus on? For example, let's say I've got a simple form contain Name, Email address, Subject and Message. I check for bad data in all of those fields and I want to put the cursor (or focus) on the first field that has an error. How does my PHP code tell Javascript that the first field in error is the Email Address or the Message or whatever? An example showing what happens in PHP and what happens in Javascript would be very handy if someone can point me to one or throw one together....
  6. I have a mostly working example of a real form I'm building for a website and would like to ask some questions about the parts I don't understand. This is my first form validation code in PHP. I'm very new to PHP but have coded in several other languages over the years, including form validation, so it's mostly a matter of learning how to do this in PHP rather than learning how to do it from scratch in my first language. The basic approach was taken from a reply to another question I asked in the Design portion of these forums. Here is my form, called topic_proposal.shtml: <html> <head> <link rel="stylesheet" type="text/css" href="css/main.css" media="screen"/> <link rel="stylesheet" type="text/css" href="css/print.css" media="print"/> </head> <body> <h1>Meeting Topic Proposal Form</h1> <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <p>Use this form to make a suggestion for a future meeting topic. All of the fields are mandatory, except for the Comments field. Complete the form and press the Submit button. To clear the form without submitting it, press the Reset button.</p> Topic proposal submitted by: <input type="text" name="proposer" size="30" value=""/></br></br> <fieldset><legend>Proposed Topic</legend> Topic Title: <input type="text" name="topic" size="50" value=""/></br></br> Author/Director: <input type="text" name="creator" size="30" value=""/></br></br> Topic Type: <select name="topic_type"> <option value="Book">Book</option> <option value="Film">Film</option> <option value="TV">TV (Movie, Series, or Miniseries)</option> <option value="Theme">Theme</option> <option value="Other">Other</option> </select></br> </fieldset> <br/><br/> <fieldset><legend>Availability</legend> Library Availability: <input type="radio" name="library_availability" value="Yes">Yes <input type="radio" name="library_availability" value="No">No <input type="radio" name="library_availability" value="N/A">N/A</br></br> Bookstore Availability (Mass-market paperback or Trade paperback): <input type="radio" name="bookstore_availability" value="Yes">Yes <input type="radio" name="bookstore_availability" value="No">No <input type="radio" name="bookstore_availability" value="N/A">N/A</br></br> </fieldset> <br/><br/> Brief Synopsis:<br> <textarea name="synopsis" rows="10" cols="50"></textarea></br></br> Additional Comments:<br> <textarea name="comments" rows="10" cols="50"></textarea></br></br> <input type="hidden" name="_submit_check" value="1"/> <input name="submitForm" id="submitForm" type="submit" value="Submit" /> <input name="reset" id="reset" type="reset" value="Reset" /> </form> </body> </html> This is the confirmation if the insert of the new row works correctly, topic_proposal_accepted.shtml: <!DOCTYPE html> <html> <head> <title>Thank You!</title> </head> <body> <h1>Thank you!</h1> <p>Your proposed topic has been added to the database. It will be considered at the next planning session. Planning sessions are typically held during the regular June and December meetings.</p> <p>You can <a href="topic_proposal.php">make another suggestion</a> or <a href="index.shtml">return to the home page</a>.</p> </body> </html> And this is the php code that shows and validates the form, topic_proposal.php: <?php $debug = 1; $Defaults = array(); $Errors = array(); include('topic_proposal.shtml'); if ($debug) { echo 'Current php version: ' . phpversion() . '<br/>'; //Gives 5.3.19 on absolut server on 2013-01-18 echo 'Request method: ' . $_SERVER['REQUEST_METHOD'] . '<br/>'; //determine request method } if ($debug) {echo "Count: " . count($_POST) . "<br/>";} /* If any of the form elements were completed, validate them. If all elements were valid, insert a record * to the database. */ if (count($_POST) > 0) { $Defaults = $_POST; $proposer = $_POST['proposer']; $topic = $_POST['topic']; $creator = $_POST['creator']; $topic_type = $_POST['topic_type']; $library_availability = $_POST['library_availability']; $bookstore_availability = $_POST['bookstore_availability']; $synopsis = $_POST['synopsis']; $comments = $_POST['comments']; if ($debug) { echo "Proposer: $proposer<br/>"; echo "Topic: $topic<br/>"; echo "Creator: $creator<br/>"; echo "Topic type: $topic_type<br/>"; echo "Library availability: $library_availability<br/>"; echo "Bookstore availability: $bookstore_availability<br/>"; echo "Synopsis: $synopsis<br/>"; echo "Comments: $comments<br/>"; } /* Verify that all mandatory fields contain data. The radio buttons and dropdown lists will inevitably contain * so assume that it is accurate. */ if (empty($proposer) || strlen(trim($proposer))==0) { $Errors[] = 'The name of the person proposing the topic is a required field. Example: Bob T.'; } if (empty($topic) || strlen(trim($topic))==0) { $Errors[] = 'The topic is a required field. Example: The War of the Worlds'; } if (empty($creator) || strlen(trim($creator))==0) { $Errors[] = 'The creator is a required field. Example: H. G. Wells'; } if (empty($synopsis) || strlen(trim($synopsis))==0) { $Errors[] = 'The synopsis is a required field. Example: A short story about the consequences of time travel.'; } /* Verify that no text field or text area contains more data than the maximum for that field. */ if (strlen(trim($proposer))>30) { $Errors[] = 'The proposer cannot exceed 30 characters. Please shorten your input.'; //colour any input over the maximum length red so user knows how short it needs to be } if (strlen(trim($topic))>50) { $Errors[] = 'The topic cannot exceed 50 characters. Please shorten your input.'; } if (strlen(trim($creator))>30) { $Errors[] = 'The creator cannot exceed 30 characters. Please shorten your input.'; } if (strlen(trim($synopsis))>500) { $Errors[] = 'The proposer cannot exceed 500 characters. Please shorten your input.'; } if (strlen(trim($comments))>500) { $Errors[] = 'The comments cannot exceed 500 characters. Please shorten your input.'; } /* Cross checks */ //If the type is Theme, library and bookstore availability must be N/A. if ($topic_type = 'Theme') { if ($library_availability = 'Yes' || ($library_availability = 'No')) { $Errors[] = "When the topic type is Theme, library availability must be N/A. Please change it."; } if ($bookstore_availability = 'Yes' || ($bookstore_availability = 'No')) { $Errors[] = "When the topic type is Theme, bookstore availability must be N/A. Please change it."; } } //If the type is Book, library and bookstore availability must be Yes or No. if ($topic_type = 'Book') { if ($library_availability = 'N/A') { $Errors[] = "When the topic type is Book, library availability must be Yes or No. Please change it."; } if ($bookstore_availability = 'N/A') { $Errors[] = "When the topic type is Book, bookstore availability must be Yes or No. Please change it."; } } if (count($Errors)==0){ echo "<h3>Your data has all been validated successfully. Attempting to insert into database...</h3>"; Insert_Proposal($proposer, $topic, $creator, $topic_type, $library_availability, $bookstore_availability, $synopsis, $comments); } else { echo "<p>The form contains errors as noted below. Please fix them and then press the Submit button again.</p>"; foreach ($Errors as $oneError) { echo "<p>" . $oneError . "</p>"; } } } function Insert_Proposal($proposer, $topic, $creator, $topic_type, $library_availability, $bookstore_availability, $synopsis, $comments) { $debug = 1; //temporary include('#php-signin-insert.shtml'); //Sign in, connect and select database $date_proposed = date('Y-m-d'); //The date is generated here, not obtained from the form. if ($debug) { echo "Date proposed: $date_proposed<br/>"; echo "Proposer: $proposer<br/>"; echo "Topic: $topic<br/>"; echo "Creator: $creator<br/>"; echo "Topic type: $topic_type<br/>"; echo "Library availability: $library_availability<br/>"; echo "Bookstore availability: $bookstore_availability<br/>"; echo "Synopsis: $synopsis<br/>"; echo "Comments: $comments<br/>"; } $insert = "INSERT INTO TopicProposals (Date_Proposed, Proposer, Topic, Creator, Topic_Type, Library_Availability, Bookstore_Availability, Synopsis, Comments) VALUES ('$date_proposed', '$proposer', '$topic', '$creator', '$topic_type', '$library_availability', '$bookstore_availability', '$synopsis', '$comments')"; echo "Insert statement: " . $insert . '<b/>'; $result = mysql_query($insert, $con); if (!$result) { throw new Exception('Insert of Topic Proposal into table failed. Please contact the webmaster. Error number: ' . mysql_errno($con) . '. Error message: ' . mysql_error($con)); } include('topic_proposal_accepted.shtml'); mysql_close($con); } ?> I won't bother showing you #php-signin-insert.shtml since it is working fine; it simply initializes a few variables, gets the connection and then selects the appropriate database. I'm also not showing you the definition of the database table since I can't think of a good reason for you wanting to see it. All the fields in the table are Varchars, except for date_proposed, which is a Date. If you execute this code, just comment out the Insert statement and the exception handling for the insert and you should be good to go. As I said, the code mostly works and will successfully insert records into the MySQL database as long as a I comment out the cross-checks involving topic_type, library_availability and bookstore_availability. That's my first question. 1. If I complete the form by choosing a topic type of Book, all four of the cross-check errors are displayed, even if I have chosen Yes or No for the bookstore and library availability radio buttons. Why? 2. If the cross-checks detect an error, the error messages are displayed but the form itself gets blanked out, as if the Reset button had been clicked. Why? 3. If the edits show no errors and the insert is successful, the "Thank you" page appears at the end of the page, not on a new page. What would I need to do put the "Thank you" page on a fresh page? 4. How can I position the cursor with PHP? I'd like to be able to set the cursor on the first error that is discovered by the edits but I'm not sure how that's done. I don't see anything (relevant) in the PHP manual when I search on "cursor". I gather I can use Javascript to set the focus but I'd rather stay pure PHP if I can. If I must use Javascript, how do I execute Javascript statements within PHP? Or can I just code them as if they were PHP statements? 5. I was going to ask if there is a debugger for PHP in Eclipse, my IDE, but Google has helped me determine that there is. Apparently it can use either Zend or XDebug. Which of the two seems to be the best? I'm running PHP 5.3.19 if that makes a difference. I should mention that I don't have a development environment on my computer; I'm using a hosting service which has PHP installed on it and that's the level they're running. That means I can't alter their setup if it isn't to my liking but, so far, that hasn't been a problem.
  7. I was sure I tried that FIRST but it never did anything. But it works perfectly now. Obviously, I miscoded it in some way.... Thank you, that was very helpful, cpd!
  8. I'm a PHP newbie (but experienced in several other languages) and I'm looking for the best way to reset a form, i.e. restore it to its initial values. I have a Reset button on the form and I know I can detect that it was pressed with if (isset($_POST['resetButton'])) { } where resetButton is the value I gave to the name attribute of the button. I just need to know how to get the various values on the form back to their original state. Typically, that would be blank for text fields and default values for radio buttons, etc. I don't know if there is a single all-purpose function that will reset everything in one go or if I have to set each field to its original value with individual statements. Either approach is fine by me. Frankly, at this stage of the game, I'd be happy to get even a not-so-good method of doing this! I have spent close to two hours googling and searching on every phrase I could think of but all I get is items about how to prevent blanks in forms; not a word on how to blank out a form field. Maybe I'm just having a Stupid Day but it shouldn't be this hard to find out how to set a field to blank! For what it's worth, I tried setting a text field to blank with this: $_POST['name'] = ''; //blank out name but nothing happened. There was no error message and the field was unchanged but I know the statement executed. I'd prefer to stay away from the klugey mess called Javascript if I can....
  9. Thanks for the example, kicken. There are a few things that aren't obvious to me from your example. 1. What is an "E_NOTICE"? You refer to them after the example but I don't see any variables with that name so I'm not sure what you mean. 2. What is the significance of the .tpl file extension on the last file? I've never seen that one before. I'm guessing it is short for "template" but I'm not sure what the effect is of executing code with a .tpl extension is in a PHP environment. 3. Is this approach safe from injection attacks? How would it have to change to be safe?
  10. I'm trying to track down one or more good examples that show a form being presented, validated and then handled, preferably all on the same page. I'm new to PHP but I've been coding in various other languages for many years so I'm definitely not new to programming. I googled on "php form handling" and found this article: http://onlamp.com/pub/a/php/2004/08/26/phpformhandling.html I've never validated a form in PHP but I like the idea of displaying, validating and then handling the validation of the form on the same page. But I'm open to arguments that this is not the best way to proceed. My big problem is that the article provides only snippets from an actual solution, not a full script. Since I'm new at PHP, I don't have the experience to imagine all the stuff that he has omitted. I've also discovered in subsequent searching that the author's approach is prone to injection attacks and I certainly want to avoid that. Therefore, I would love to find some COMPLETE examples that show all displaying, validating and handling of the data in the form. The example should use the techniques that best avoid injection attacks. For what it's worth, my form will prompt the user for some information about proposed meeting topics for a book discussion club, and validate to make sure the user has completed the form correctly. If the user has made errors, I'd like to display the errors to him on the same page as the form so that he can make the appropriate changes and then resubmit. Once the data checks out as vaild, I will insert a row to a table in a MySQL database. I'm fluent with HTML and database so displaying the form and inserting the row into the database table are well within my grasp. I don't need any major amount of instruction there. But the proper techniques to validate the data and display errors on the same page as the form is something I've never done in PHP. (I have done it in Java servlets running in Tomcat and in mainframe applications but the techniques seem rather different for PHP.)
  11. Premiso, xyph and Maq: I was apparently mistaken about Ajax and XQuery - I had assumed they were server-side and needed to be installed on the server to be usable - but I assure you that I'm not delusional ;-) Psycho: Although I don't mind learning new things, I don't know if I want to learn a possibly complex new thing like Ajax or XQuery just to be able to do a routine job. As you say, I'm just showing some simple data that I want the user to be able to page and sort. If I can do that without having to learn something like Ajax or XQuery, I'm inclined to do it. After all, I'm already new to PHP so I'm inclined to keep it within MySQL and PHP if I can. (For what's its worth, I'm very familiar with SQL having taught it professionally for several years so I'm not worried about that part of the job.) Can anyone suggest examples or existing code that already does what I want it to do? It would save me time to at least start with that, though I'd likely tweak it a bit to get exactly what I want.
  12. Thanks Maq and kicken! I got the backticks to work by following your suggestion. I wanted to do that just in case MySQL didn't want to let me change the column name. Then I successfully changed the column name and took the backticks out again because changing the column name was definitely the best way to proceed. The article on error handling was also very helpful. I can see it's going to take a bit of time to evolve a good, clean error handling style, just as it has with Java. But I'm started down the right road now, thanks to your suggestion.
  13. Many thanks, kicken!! Two things. First, can you tell me WHERE to backtick "Character" in this case? Would I do it in the form itself? Or in the assignment statement for $SortKey? Or in the assignment statement for $result? Will having the backticks in either of the latter two assignment statements mess up the behaviour of the other columns given that they aren't reserved words? Second, how do I do the error handling for the fetch? With a try/catch block? Or is there a better way?
  14. I'm looking for some design ideas on how to handle a situation on a website I am building. On one of my pages, I want to display a table of data. The volume of data will be something in the neighbourhood of 400 rows and it will grow at the rate of one row per month. I expect to put the data in a MySQL table. My users are going to want to look at the data in different sequences. The data is a list of meeting topics which our book discussion club has had over the past 30-odd years. Some users will want to see the data in chronological order from earliest topic to latest. Some will want to see it in order by the author name. Some will want to see it in order by the name of the person who presented the discussion. I'd like to accomodate all of them as cleanly and efficiently as I can. The data is on a server owned by a hosting service. They have PHP and MySQL but they don't have Ajax, JQuery or other tools and it looks like they won't let me install such tools. Setting up my own server is not an option at this point so I need to solve this problem with just PHP and MySQL. Ideally, I'd like to display the data initially in a default order (chronological order by meeting date) but let the user get the data re-sorted in any of the four sequences I've described by clicking on something. I could do this easily enough in Java but don't know the best way to accomplish it in PHP. Perhaps having a clickable column name with an up arrow and a down arrow to control sort sequence - like Thunderbird. Or maybe I need to use a form and make the user select the sequence with a set of radio buttons. I can't be the first guy who has needed to do this so I thought I'd ask the experts for the best way forward. If anyone can point me to an actual example that is close to what I want to do, that would be an added bonus :-)
  15. I'm encountering some inconsistent behaviour with respect to variable substitution. I hope someone here can help me figure out why. Let me explain what I'm trying to do. I am working on a prototype that is supposed to display a simple three-column MySQL table in ascending order by one or the other of the three columns. Exactly the same data (rows and columns) is shown each time; only the sequence of the rows differs. To accomplish this, I show the user a form with three radio buttons in a single group. The user chooses the radio button that represents the column which is to be used in the sort, then presses Submit. That invokes a script that contains PHP. The script reads the value passed from the form, which is the name of one of the three columns of the table, Series, Character, or Actor. and stores it in a variable name $SortKey. Then, the variable is used in ORDER BY clause of the SQL Query to cause sorting on that column. This all works perfectly for the first and third columns, Series and Actor. But when script executes for the column named Character, the result is an empty table. There is no error message of any kind. I'm baffled by this. Obviously, my approach is correct otherwise the first and third columns would fail as well. But I can't see anything different about the second column. I'm very new to PHP but know HTML quite well and have substantial experience with Java and a little bit with Perl so I'm not new to programming by a long shot. Here's the form, which is called Captains_form.php: <html> <head> <link rel="stylesheet" type="text/css" href="css/main.css" media="screen"/> <link rel="stylesheet" type="text/css" href="css/print.css" media="print"/> </head> <body> <h1>Enterprise Captains</h1> <p>You can view the list of Enterprise Captains in any of the following sequences:</p> <form action="Captains.php" method="post"> <input type="radio" name="sort" value="Series" /> Series (ascending)<br /> <input type="radio" name="sort" value="Character" /> Character (ascending)<br /> <input type="radio" name="sort" value="Actor" /> Actor (ascending)<br /> <input type="submit" /> </form> </body> </html> Here's the script, which is called Captains.php: <html> <head> <link rel="stylesheet" type="text/css" href="css/main.css" media="screen"/> <link rel="stylesheet" type="text/css" href="css/print.css" media="print"/> </head> <body> <h2>Enterprise Captains List</h2> <?php $con = mysql_connect("localhost:3306","my_All","******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_Sandbox", $con); //echo $_POST["sort"]; $SortKey=$_POST["sort"]; $result = mysql_query("SELECT * FROM Captains order by $SortKey"); echo "<table border='1' cellpadding='5' cellspacing='0'>"; echo "<tr class='heading'><th>Series</th><th>Character</th><th>Actor</th></tr>"; while($row = mysql_fetch_array($result)) { echo "<tr class='detail'><td>" . $row['Series'] . "</td><td>" . $row['Character'] . "</td><td>" . $row['Actor'] . "</td></tr>"; } echo "</table>"; mysql_close($con); ?> </body> </html> Can anyone tell me why the second column, Character, produces an empty result when I select it on the form? Also, if there is an error message being produced when the query executes, how can I get it? I think I'm handing errors in the connection correctly but I'm not sure how to detect an error in the execution of the query.
×
×
  • 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.