Jump to content
Larry Ullman's Book Forums

Christopher Bergin

Members
  • Posts

    90
  • Joined

  • Last visited

Everything posted by Christopher Bergin

  1. no I didn't. I did a print_r{$user} and it confirmed that the object was converted to a string. I was able to pass the string in a standard <a href> tag as the values appeared in the URL. So the problem seemed to be with the header function. Anyway, once I passed the serialized object to another page, the script failed to unserialize it so I abandoned the idea of passing an object in a URL and simply appended the id value to a link and instantiated a new object on the other page using a $_GET['id'] value as a reference. I was still able to adhere to the MVC paradigm.
  2. I couldn't get my sessions to work while trying to replicate the exercise in this chapter so I attempted to pass values using a URL. I ran into problems when trying to pass an object value, so I serialized the value and tried to append it onto the URL. The error I'm receiving is the following: Warning: Header may not contain NUL bytes in PHP test/login.php on line 31. Can anyone offer insight regarding the error? // Check for a form submission: if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form submission // Validate the form data: if ($form->validate()) { // Check against the database: $q = 'SELECT id, userType, username, email FROM users WHERE email=:email AND pass=SHA1(:pass)'; $stmt = $pdo->prepare($q); $r = $stmt->execute(array(':email' => $email->getValue(), ':pass' => $password->getValue())); // Try to fetch the results: if ($r) { $stmt->setFetchMode(PDO::FETCH_CLASS, 'User'); $user = $stmt->fetch(); } // Store the user in the session and redirect: if ($user) { // Store in a session: //$_SESSION['user'] = $user; // Redirect: $user = serialize($user); header("location:index.php?user=$user"); exit; } } // End of form validation IF.
  3. well, the SQL query works correctly because the conditional statement executes as it's designed to do. I only wanted to modify the conditional to force the script to execute the exception part of the block just to see the results. What confused me was that when the conditional statement was modified so that the row count was equivalent to 0, I would receive an error but when I modified the statement so that the row count was less than 0, it executed the exception part of the code. It's not important. The code works fine so I'll leave it at that.
  4. Another question, in script 9.11, the author assigns values to parameters to be used in a prepared statement query: // Check against the database: $q = 'SELECT id, userType, username, email FROM users WHERE email=:email AND pass=SHA1(:pass)'; $stmt = $pdo->prepare($q); $r = $stmt->execute(array(':email' => $email->getValue(), ':pass' => $password->getValue())); I received an error so I simply used the values of email and password and the script worked. Is the getValue() method inherent within the PDO class? nevermind, I found the answer right in front of me.
  5. I was trying to force an error on the following script in order to execute the catch routine by replacing the conditional statement if ($r && $r->rowCount() > 0) with if ($r && $r->rowCount() = 0) and for some reason, I received the ubiquitous 500 Internal Server Error. It wasn't until I modified the conditional to read if ($r && $r->rowCount() < 0) would the catch routine be executed. Any idea why this might have happened? try { $q = 'SELECT id, title, content, DATE_FORMAT(dateAdded, "%e %M %Y") AS dateAdded FROM pages ORDER BY dateAdded DESC LIMIT 3'; $r = $pdo->query($q); // Check that rows were returned: if ($r && $r->rowCount() > 0) { // Set the fetch mode: $r->setFetchMode(PDO::FETCH_CLASS, 'Page'); // Records will be fetched in the view: include('views/index.html'); } else { // Problem! throw new Exception('No content is available to be viewed at this time.'); } } catch (Exception $e) { // Catch generic Exceptions. include('views/error.html'); }
  6. Yes, I have other scripts in the same directory that run once the errors are corrected. It hasn't prevented me from resolving runtime issues because sometimes I'll place the error detection script into the class definition script and get some sort of confirmation that the origin of the error is somewhere in the class definition. But the main calling script, when run, will at times just issue the 'Internal Server Error' message without any indication of the source of the error. I suppose I could check the server error log but I just thought I'd put it out there.
  7. I'm finding it difficult to view errors and I'm wondering if it's due to OOP interface. I didn't seem to have this problem with procedural programming. The error I seem to be seeing often is 500 Internal Server Error and sometimes it turns out to be a simple syntax error. I've been using this script in the code but it doesn't work consistently: // Display errors ini_set('display_errors', 1); // Full error reporting error_reporting(E_ALL); I'm using a hosting service that has PHP 5.3.13 installed. Any suggestions? Also, Script 8.3 demonstrates the idea of extending the Exception class. To provide a more detailed list of errors, a class extending the Exception class is created and the getDetails method is defined to account for common errors. What I don't understand is how the method is called. In the attendant class WriteToFile, conditions are evaluated and exceptions are thrown to the FileException class but not the getDetails function specifically. if (empty($file)) throw new FileException($this->_message, 0); Also, the conditional operator in the switch statement references a variable but I don't see it declared anywhere. switch ($this->code) here is the entire class definition: <?php # Script 8.3 - WriteToFile2.php // This page defines a WriteToFile and a FileException class. /* The FileException class. * The class creates one new method: getDetails(). */ class FileException extends Exception { // For returning more detailed error messages: function getDetails() { // Return a different message based upon the code: switch ($this->code) { case 0: return 'No filename was provided'; break; case 1: return 'The file does not exist.'; break; case 2: return 'The file is not a file.'; break; case 3: return 'The file is not writable.'; break; case 4: return 'An invalid mode was provided.'; break; case 5: return 'The data could not be written.'; break; case 6: return 'The file could not be closed.'; break; default: return 'No further information is available.'; break; } // End of SWITCH. } // End of getDetails() method. } // End of FileException class. /* The WriteToFile class. * The class contains one attribute: $_fp. * The class contains three methods: __construct(), write(), close(), and __destruct(). */ class WriteToFile { // For storing the file pointer: private $ = NULL; // For storing an error message: private $_message = ''; // Constructor opens the file: function __construct($file = null, $mode = 'w') { // Assign the file name and mode // to the message attribute: $this->_message = "File: $file Mode: $mode"; // Make sure a file name was provided: if (empty($file)) throw new FileException($this->_message, 0); // Make sure the file exists: if (!file_exists($file)) throw new FileException($this->_message, 1); // Make sure the file is a file: if (!is_file($file)) throw new FileException($this->_message, 2); // Make sure the file is writable, when necessary if (!is_writable($file)) throw new FileException($this->_message, 3); // Validate the mode: if (!in_array($mode, array('a', 'a+', 'w', 'w+'))) throw new FileException($this->_message, 4); // Open the file: $this->_fp = fopen($file, $mode); } // End of constructor. // This method writes data to the file: function write($data) { // Confirm the write: if (@!fwrite($this->_fp, $data . "\n")) throw new FileException($this->_message . " Data: $data", 5); } // End of write() method. // This method closes the file: function close() { // Make sure it's open: if ($this->_fp) { if (@!fclose($this->_fp)) throw new FileException($this->_message, 6); $this->_fp = NULL; } } // End of close() method. // The destructor calls close(), just in case: function __destruct() { $this->close(); } // End of destructor. } // End of WriteToFile class. Regarding the section on the Autoloader function, (script 8.10) I realized that the class name must be identical to the file name in order for the function to properly work. I originally had the ShapeFactory class within the shapefactory file and received no errors when initially run using the standard require statement.
  8. I was trying to exploit the restrictive behavior of the Singleton pattern by attempting to create an object using a standard call to the __construct method: $CONFIG = new Config(). I was expecting to receive an error but nothing happened. No error and no output. Web site instances are iterations of a web site running on multiple servers. Typically, the instances would be load balanced to attenuate traffic and maintain accessibility.
  9. I tried to force an error by assigning the variable $CONFIG to the class Config but for some reason, the output didn't generate an error, it simply didn't display anything. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> </head> <body> <h2>Using a Singleton Config Object</h2> <?php require('Chapter7_Config.php'); //$CONFIG = Config::getInstance(); $CONFIG = new Config(); $CONFIG->set('live', 'true'); echo '<p>$CONFIG["live"]: ' . $CONFIG->get("live") . '</p>'; $TEST = Config::getInstance(); echo "<p>$TEST['live']: " . $TEST->get('live') . "</p>"; unset($CONFIG, $TEST); ?> </body> </html> class Config { // Store a single instance of this class: static private $_instance = NULL; // Store settings: private $_settings = array(); // Private methods cannot be called: private function __construct() {} private function __clone() {} // Method for returning the instance: static function getInstance() { if (self::$_instance == NULL) { self::$_instance = new Config(); } return self::$_instance; } // Method for defining a setting settings: function set($index, $value) { $this->_settings[$index] = $value; } // Method for retrieving a setting: function get($index) { return $this->_settings[$index]; } } // End of Config class definition. Also, I was just wondering if this design pattern would be typical of web instances or database instances being distributed over multiple servers.
  10. thank-you Antonio, your error script pointed me to an incorrect directory setting in my include file. Everything works now. I'm going to hold on to that little nugget of code.
  11. yes, version 5.3.13. It's not important. I just thought I'd put it out there. I was able to recover the cgiErrorlog so I'll examine that.
  12. I've been trying to complete the exercise in Chapter 6 pertaining to namespaces.(scripts 6.9, 6.10) When attempting to run the script, I initially received an error like this: Warning: Unexpected character in input: '\' (ASCII=92) state=1; I even tried running the author's scripts and received the same error. After looking on the PHP site for more information, I tried deleting the initial '\' to the first object instantiation at the line number where the error specified: $hr = new MyNamespace\Company\Department('Accounting'); This resulted in a blank page. Further tinkering around resulted in an Internal Server Error. Since I'm using a hosting service, I've sent them an inquiry for directions to access the server log. In the meantime, I was wondering if anyone could shed light on this issue. The directory was configured as the book suggested. The version of PHP that I'm using is 5.3.
  13. a sidebar in Chapter 6 mentions that including a __toString method in the definition of a class can be an effective way to print the value of an object of the class if the object is used as a string; typically for debugging purposes. $a = new SomeClass(); echo $a; I tried to invoke this in script 6.4 but received the following error: Catchable fatal error Method User::__toString() must return a string value in Chapter6_interface.php. Can anyone tell me what I'm doing wrong? I just displayed the pertinent segments of code to avoid confusion. class User implements iCrud { private $_userId = NULL; private $_username = NULL; function __toString() { } // Constructor takes an array of data: function __construct($data) { $this->_userId = uniqid(); $this->_username = $data['username']; } // End of constructor. // Identify the user information: $user = array('username' => 'trout'); // Print a little introduction: echo "<h2>Creating a New User</h2>"; // Create a new User: $me = new User($user); echo $me;
  14. thanks, that explains a few things. I guess I was wondering if XML was considered legacy technology at this point. I learned it years ago but never kept up with it. I'll augment my knowledge of Ajax by learning JSON.
  15. I was having a difficult time getting the script to work. The error I was receiving on Firefox was: message[0] is undefined results.innerHTML = message[0].firstChild.nodeValue; The error appearing on Safari was more stringent with the initialization of the message variable but citing the same result. The message variable was receiving a value of undefined. Which led me to wonder if the PHP script was returning a value. When printing the value of the data variable, the value was null. When I changed the value of data from responseXML to responseText and printed it out, it provided me with additional information that indicated a database issue. Which leads me to my first question, is there a suggested way to test a PHP script while it is attached to an Ajax script? Printing the values of PHP variables doesn't seem to work since all output must get sent to the Ajax script. Also, does it matter in the script where the handleResponse function is called? It would seem to me that sending data to the PHP script via ajax.send(values) instruction would precede a call to check the response status. Anyway, all set here. On another note, is XML technology still widely used? // add_employee.js /* This page does all the magic for applying * Ajax to an "add an employee" form. * The form data is sent to a PHP * script using the POST method. * The PHP script sends back a response in XML format. */ // Have a function run after the page loads: window.onload = init; // Function that adds the Ajax layer: function init() { // Get an XMLHttpRequest object: var ajax = getXMLHttpRequestObject(); // Attach the function call to the form submission, if supported: if (ajax) { // Check for DOM support: if (document.getElementById('results')) { // Add an onsubmit event handler to the form: document.getElementById('emp_form').onsubmit = function() { // Call the PHP script. // Use the POST method. // Open the connection: ajax.open('post', 'add_employee_xml.php'); // Function that handles the response: ajax.onreadystatechange = function() { // Pass it this request object: handleResponse(ajax); } // Assemble all the form data: var fields = ['first_name', 'last_name', 'email', 'department_id', 'phone_ext]; for (var i = 0; i < fields.length; i++) { fields = fields + '=' + encodeURIComponent(document.getElementById(fields).value); } var values = fields.join('&'); // Set the request headers: ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Send the request along with the data: ajax.send(values); return false; // So form isn't submitted. } // End of anonymous function. } // End of DOM check. } // End of ajax IF. } // End of init() function. // Function that handles the response from the PHP script: function handleResponse(ajax) { // Check that the transaction is complete: if (ajax.readyState == 4) { // Check for a valid HTTP status code: if ((ajax.status == 200) || (ajax.status == 304) ) { var results = document.getElementById('results'); // Reset all the labels: document.getElementById('first_name_label').className = 'title'; document.getElementById('last_name_label').className = 'title'; document.getElementById('email_label').className = 'title'; document.getElementById('department_id_label').className = 'title'; document.getElementById('phone_ext_label').className = 'title'; // Get the XML data: var data = ajax.responseXML; // Get the main response: var message = data.getElementsByTagName('result'); // Get all the errors: var errors = data.getElementsByTagName('error'); // Temp variable to use in the loop: var temp = false; // Loop through each error: for (var i = 0; i < errors.length; i++) { // Get the error value: temp = errors.firstChild.nodeValue; // Change the class: document.getElementById(temp + '_label').className = 'error'; } // End of FOR loop. // Put the received response in the DOM: results.innerHTML = message[0].firstChild.nodeValue; // Make the results box visible: results.style.display = 'block'; } else { // Bad status code, submit the form. document.getElementById('emp_form').submit(); } } // End of readyState IF. } // End of handleResponse() function.
  16. I agree. Posting a confirmation message before it completes the PHP script is a bit premature, if not irresponsible. But I had to try.
  17. yes, that is what's going on. I didn't know how else to trigger the form submission to the PHP script without returning a value of true from the function, in which case, the message wouldn't appear. If the value of the function returned false, the form wouldn't get submitted, right? So, I forced the submission after 6 seconds and allowed the function to return false.
  18. I noticed in chapter 4 that the author includes a value of NULL when inserting a record into a database table in which the field corresponding to the NULL value is defined as a primary key whose value is not NULL. $query = "INSERT INTO employees VALUES (NULL, $did, '$fn', '$ln', '$e', $ext)";
  19. I was able to get the message to display for 6 seconds before the submission of the form, all without having to use an Ajax object. function errorCheck() { var success= document.getElementById('success'); var email= document.getElementById('email'); var message = document.getElementById('message'); if ((email.value.length > 6) && (email.value.search('@') > 0)) { success.textContent= 'your request has been sent'; setTimeout(function(){ document.getElementById('formstyle').submit(); },6000); } else message.textContent= ' invalid email address'; return false; } document.forms[0].onsubmit= errorCheck;
  20. yes, it's finally beginning to sink in. Thanks for clarifying.
  21. the lesson in chapter 3 includes a script dept.js, that calls function init which in turn calls function handleResponse to determine the response code from an Ajax request. // Function that adds the Ajax layer: function init() { // Get an XMLHttpRequest object: var ajax = getXMLHttpRequestObject(); // Attach the function call to the form submission, if supported: if (ajax) { // Check for DOM support: if (document.getElementById('results')) { // Add an onsubmit event handler to the form: document.getElementById('dept_form').onsubmit = function() { // Call the PHP script. // Use the GET method. // Pass the department_id in the URL. // Get the department_id: var did = document.getElementById('did').value; // Open the connection: ajax.open('get', 'dept_results_ajax.php?did=' + encodeURIComponent(did)); // Function that handles the response: ajax.onreadystatechange = function() { // Pass it this request object: handleResponse(ajax); } // Send the request: ajax.send(null); return false; // So form isn't submitted. } // End of anonymous function. } // End of DOM check. } // End of ajax IF. } // End of init() function. // Function that handles the response from the PHP script: function handleResponse(ajax) { // Check that the transaction is complete: if (ajax.readyState == 4) { // Check for a valid HTTP status code: if ((ajax.status == 200) || (ajax.status == 304) ) { // Put the received response in the DOM: var results = document.getElementById('results'); results.innerHTML = ajax.responseText; // Make the results box visible: results.style.display = 'block'; } else { // Bad status code, submit the form. document.getElementById('dept_form').submit(); } } // End of readyState IF. } // End of handleResponse() function. The author wraps the function call to handleResponse in an anonymous function. I tried to simply call the function like this: // Function that handles the response: ajax.onreadystatechange = handleResponse(ajax); but it wouldn't work and I don't understand why. Is this an example of an event receiving a function definition and not the actual result?
  22. At the risk of sounding obtuse, do you have any idea what the code would look like?
  23. Can anyone think of a way to delay the return of a Javascript function? I'm trying to perform a quick email validation using Javascript. If the email is valid, I would like to send a success message to the HTML document. (it's actually a PHP document that includes the form) The success message flashes on the screen for a second before vanishing. I would like the message to remain for perhaps 6 seconds before disappearing. The message indicating an invalid email remains on the screen because the Javascript function in that particular instance returns a value of false. It's when the function returns a value of true that the message becomes a blip. I tried using a setTimeout function but the way I'm trying to use it doesn't work. The HTML form has an ID of 'formstyle'. Here is the function: function errorCheck() { var email= document.getElementById('email'); var success= document.getElementById('success'); var status; if ((email.value.length > 6) && (email.value.search('@') > 0)) { success.textContent= 'your request has been sent!'; status= setTimeout('return true', 6000); } else {message.textContent= ' invalid email address'; return false; } } document.getElementById('formstyle').onsubmit= errorCheck;
  24. I can't say for sure but I think the web server that I'm using with a hosting service is not properly updating saved documents that I'm editing. I happen to have 2 web sites each with it's own domain and with the same hosting service. When it appears that the document (php) I'm editing and saving to this one questionable server isn't updating, I'm able to save and test the same document on my other site and see changes immediately. I'm constantly clearing the cache on my browser so it isn't that. I'm able to edit the document directly on the server so the code reflects the changes once I save it. Is it possible that a setting on the server is caching these pages and referencing them? Is this something I can mention to the hosting service support center to have looked at and adjusted?
×
×
  • Create New...