PHP - Throw Exception Not Working. What I'm Doing Wrong?
Similar TutorialsGett an error from some custom code I inherited in a WordPress installation. Here is the error... Code: [Select] Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct() [<a href='datetime.--construct'>datetime.--construct</a>]: Failed to parse time string (--) at position 0 (-): Unexpected character' in /home2/history8/public_html/bee/wp-content/themes/makinghistoryblue/beeteachers.php:27 Stack trace: #0 /home2/history8/public_html/bee/wp-content/themes/makinghistoryblue/beeteachers.php(27): DateTime->__construct('--') #1 /home2/history8/public_html/bee/wp-includes/plugin.php(395): bee_teachers('') #2 /home2/history8/public_html/bee/wp-admin/admin.php(151): do_action('bee_teachers', Array) #3 {main} thrown in /home2/history8/public_html/bee/wp-content/themes/makinghistoryblue/beeteachers.php on line 27 Here is the code... Code: [Select] <?php $teachers = $wpdb->get_results("SELECT * FROM bee_teachers,bee_postmeta WHERE bee_teachers.statebee=bee_postmeta.post_id and meta_key='regional_date' ORDER BY meta_value ASC"); $today = new DateTime(); foreach ($teachers as $teacher): $site = get_post($teacher->statebee)->post_title; $date = new DateTime($teacher->meta_value); // this is line 27, mentioned in the error if($date<$today) $style=' style="color:#999"'; else $style=''; ?> If I remm out these lines, the query works, just no styling difference based upon date... Code: [Select] $date = new DateTime($teacher->meta_value); // this is line 27, mentioned in the error if($date<$today) $style=' style="color:#999"'; else $style=''; Thoughts? This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=358486.0 My sql limits are not working. In "select * from state order by state limit 18,36", state is not limiting till 36 but goes till 54 and prints it completely.My sql statement seems to be right. Is there any problem with my php ? When i debug my $check = 36 but it should be 18 ($check is just the variable to show how many values it is printing). Can someone please point me my mistake ? Code: [Select] <table> <tr> <td> <?php $sql = "select * from state order by state limit 0,18"; $dat = mysql_query($sql); while($row = mysql_fetch_array($dat)) { $state=$row['state']; ?> <p><span> • </span> <a href="<?php echo $state; ?>-1.html"><strong><?php echo $state; ?></strong></a> <?php } ?> </p> </td> <td> <?php $sql = "select * from state order by state limit 18,36"; $check = 0; // used this to check $dat = mysql_query($sql); while($row = mysql_fetch_array($dat)) { $check++; // incrementing this value after each display $state=$row['state']; ?> <p><span> • </span> <a href="<?php echo $state; ?>-1.html"><strong><?php echo $state; ?></strong></a> <?php } ?> </td> </tr> </table> Hello dears, I've tried to use htmlspecialchars or htmlentities but both no longer work ! Example1 : Code: [Select] <?php $new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES); echo $new; ?> Output should <a href='test'>Test</a> Code: [Select] <?php $str = "A 'quote' is <b>bold</b>"; echo htmlentities($str); ?> Output should A 'quote' is <b>bold</b> But it isn't working ? what is wrong ? Hello! This may sound like a stupid question but i have been trying to get this working all day and its driving me crazy.
Ive been asked to take over development of this project, he sent me his code and its a little out of date so im trying to update it. Here is what i cant work out.
I have this little snippet of code:
if ($page == "showthread"){ showThread(); }There are several more like that, but you dont need a whole list. That code seems to be throwing up this error when i go to that specific page: Notice: Undefined index: error in ..... All well and good, i would usually do this: if (isset($page) == "showthread"){ showThread(); }Thats fine and dandy, the error goes away. But now, when i go to that page, it redirects me and gives me my error message for a non-existing page. Its really frustrating me. Can you help me fix this little error? I have developed a code for a login and seems to work well (No syntax error according to https://phpcodechecker.com/ but when I enter a username and a password in the login form, I get an error HTTP 500. I think that everything is ok in the code but obviously there is something that I am not thinking about. The code (excluding db connection): $id="''"; $username = $_POST['username']; $password = md5($_POST['password']); $func = "SELECT contrasena FROM users WHERE username='$username'"; $realpassask = $conn->query($func); $realpassaskres = $realpassask->fetch_assoc(); $realpass= $realpassaskres[contrasena]; $func2 = "SELECT bloqueado FROM users WHERE username='$username'"; $blockedask = $conn->query($func2); $blockedres = $blockedask->fetch_assoc(); $bloqueado = $blockedres[bloqueado];
//Login if(!empty($username)) { // Check the email with database So basically I have a function that grabs a daily bible scripture via an rss feed. For whatever reason, it is offline today and I was greeted with a huge paragraph of errors and the bottom part of my page not rendering. Here is the function: Code: [Select] <?php function scripture(){ function fetchXML($url) { $ch = curl_init(); $useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_USERAGENT, $useragent); //get data $data = curl_exec($ch); curl_close($ch); return $data; } define("USE_CURL", true); $url = "http://www.mybiblescripture.com/rss/bible.php?fmt=daily&trans=KJV"; //get xml doc with info $data = fetchXML($url); //create a SimpleXML object to parse the xml $char_xml = new SimpleXmlElement($data); $scripture_a=$char_xml->channel->item->description; $scripture_b=$char_xml->channel->item->title; echo $scripture_a . '<br><b>'. $scripture_b. '</b>'; } ?> And here is the nasty error I receive due to the url being offline: Code: [Select] Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /path/lbcfunc.php:21 Stack trace: #0 /path/lbcfunc.php(21): SimpleXMLElement->__construct('') #1 /path/index.php(31): scripture() #2 {main} thrown in /path/lbcfunc.php on line 21 I have 0 experience in catching exceptions and unsure where to start. I would like to try and just echo: "No Bible Scripture Found" as a friendly message instead I guess. thanks. Hi ! I was seeing the Exception class defined in basic.php and I found that all the methods are final and without body: Code: [Select] final public function getMessage () {}But if I call MyCustomException->getMessage() I get the message. How does it works?? Hey, I'm wondering what the issue is, I'm new to using PDO and objects so I'm sure this is a common error but setting me on the right track would be greatly appreciated. Code: [Select] Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND password = d41d8cd98f00b204e9800998ecf8427e' at line 1' in /Users/JPFoster/Sites/Jaipai.Blog/engine.php:47 Stack trace: #0 /Users/JPFoster/Sites/Jaipai.Blog/engine.php(47): PDO->query('SELECT * FROM u...') #1 /Users/JPFoster/Sites/Jaipai.Blog/index.php(7): SiteEngine->login('', '') #2 {main} thrown in /Users/JPFoster/Sites/Jaipai.Blog/engine.php on line 47 Code: [Select] public function login($user, $pw){ $user = addslashes($this->user); $pw = md5($pw); $query = "SELECT * FROM users WHERE username = ".$user." AND password = ".$pw; //set up query $results = $this->pdo->query($query); $num_rows = $results->num_rows; if ($num_rows == 1){ $row = $results->fetch_assoc(); echo "Worked!"; //$this->set_session($row['id'], $row['username'], $row['email']); } else { echo "Your Username and Password did not match"; } //if user + passs match { redirect (member page) and set up sessions // Else ... Retry... } } I don't see an issue with my query, and the object is instantiated by having the submit button isset() and i use login($_post[user], $_post[pw]) Hey Guys. I am across this in a book and I am having a hard time understanding how I can try/catch this expception
The code below will throw an exception if I add an unit object into Archer or LaserCannon object.
Here is a quick example
class UnitException extends Exception{} abstract class Unit{ function AddUnit(Unit $unit){ throw new UnitException(get_class($this)."is a leaf"); } function removeUnit(Unit $unit){ throw new UnitException(get_class($this)."is a leaf"); } abstract function bombardStrength(); } class Archer extends Unit { function bombardStrength(){ return 4; } } class LaserCannonUnit extends Unit { function bombardStrength(){ return 44; } } $laser_cannon = new LaserCannonUnit(); $laser_cannon->AddUnit(New Archer()); // This is not allowedWhen I run the client code I get the following error message Fatal error: Uncaught exception 'UnitException' with message 'LaserCannonUnitis a leaf' Can any please help me understand this?? Thanks! at this point, I've authenticated with the login service, and I believe I'm now passing the cookie correctly to the ADBAccess service, but when I do a soapcall to getCMSData, I'm getting an exception. Here's the relevant code: $agDataService->__setCookie('cookie', $s_Cookie); $a_includeList[0]="*"; $a_getCMSTables_args['opName']='accounts'; $a_getCMSTables_args['startDate']='01/07/2011'; $a_getCMSTables_args['endDate']='01/08/2011'; $a_getCMSTables_args['lastID']=''; $a_getCMSTables_args['includeList']= a_includeList; $agTables = $agDataService->__soapCall('getCMSData', $a_getCMSTables_args, null, new SoapHeader('http://webservice.agemni.com', 'cookie', $s_Cookie)); and here's the exception: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.NullReferenceException: Object reference not set to an instance of an object. at ADBAccess.setErrorXML(XmlDocument& responseDoc, XmlElement& DocRoot, String ErrorMessage, Int32 ErrorNum, Int32 numRecords) at ADBAccess.getCMSData(String opName, String startDate, String endDate, String lastID, String[] includeList) --- End of inner exception stack trace --- any ideas? How to get cURL timedout Exception or cURL timedout Message ? hello to all,
My issue is that i have a script encoded with zend and the script some pages work some are just BLANK
Zend it is installed :
This program makes use of the Zend Scripting Language Engine: Zend Engine v2.4.0, Copyright © 1998-2014 Zend Technologies with the ionCube PHP Loader v4.7.1, Copyright © 2002-2014, by ionCube Ltd., and with Zend Guard Loader v3.3, Copyright © 1998-2013, by Zend Technologies Configuration File (php.ini) Path /usr/local/lib Loaded Configuration File /usr/local/lib/php.ini and Its throwing exception he Can someone please help cuz i am tryin like a week to fix it but no results Edited by SSopranos, 07 January 2015 - 02:21 PM. Hi guys, I'm reviewing a piece of small web application and the current application does not have any error / exception handling capability. If there is any error, it would simply show an error message followed by die;. I'm planning to implement a simple exception handling class to handle the errors. What I'm thinking is a simple redirect when an error is being caught together with an error code that correspond to an error message in a simple flat text file. The error page will then show an error message that corresponds to the code. Here's what I have so far. Would appreciate if the PHP experts here would give simple pointers to enhance it. <?php class MyException extends Exception {} try { throw new MyException("error.php"); } catch (MyException $e) { $file = $e->getMessage(); header("Location: $file?e=1"); } ?> This is what I have on my error.php page <?php $errorcode = $_GET['e']; function getErrorMessage($errorcode) { $errors = file("english.txt"); foreach ($errors as $error) { list ($key,$value) = explode(",",$error,2); $errorArray[$key] = $value; } return $errorArray[$errorcode]; } echo "Test <br />"; echo getMessageMap($errorcode); ?> As you can see here, exception class would redirect user to error.php if an error is caught together with a GET variable on the URL. On error.php page, it would GET the error code and then run it through a function to get the error message of the corresponding error code and then echos it out. Was wondering if this is a good practice? My ultimate goal here is to avoid displaying the error message itself on private includes file. Thank you in advance for your suggestions. This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=310162.0 I am working to echo the results in a while or for loop... Both of my sample codes work, but the results are wrong! The while loop ONLY echos a result IF the first record in the postings table matches the id passed (does not display a result unless the first record has a match) The if loop displays ALL listings with the same name (counts them all) so there are no unique listings! <?php $posts_by_city_sql = "SELECT * FROM postings WHERE id='$_GET[id]'"; $posts_by_city_results = (mysqli_query($cxn, $posts_by_city_sql)) or die("Was not able to grab the Postings!"); /* While Loop */ while($posts_by_city_row = mysqli_fetch_array($posts_by_city_results)) { echo "<li><a href='posting_details.php?id=$posts_by_city_row[id]'>$posts_by_city_row[title]</a></li>"; } /* For Loop */ $posts_by_city_row = mysqli_fetch_array($posts_by_city_results); for ($i=0; $i<sizeof($posts_by_city_row); $i++) { echo "<li><a href='posting_details.php?id=$posts_by_city_row[id]'>$posts_by_city_row[title]</a></li>"; } ?> Results with for loop (there are 7 total unique book names, but it's just counting the first match on id 7 times like below): AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners In drive.php
public function insert($postBody, $optParams = array()) I am querying... $sql = "SELECT `messages_inbox`.`message_id`, `users`.`firstname`, `users`.`lastname`, `users`.`username` AS `from`, '${user_info['username']}' AS `to`, `subject`, LENGTH(`files`) AS `len`, 'inbox' AS `box`, DATE_FORMAT(`messages_inbox`.`time` ,'%T %D-%M-%Y') AS `time` "; $sql .= "FROM `messages_inbox` INNER JOIN `users` ON `messages_inbox`.`from_id` = `users`.`id` WHERE `to_id` = ${user_info['uid']} AND `messages_inbox`.`deleted` = 0 ORDER BY `messages_inbox`.`message_id` DESC"; and I am trying to output $displayName = ucwords("${message['firstname']} ${message['lastname']}"); by using $messages = pm_fetch_all($_GET['box']); I know my fetch works but for some reason firstname and lastname are only returning the logged in users first name and last name, not the person who sent the message. I'm sure it's not much, but I'm not understanding something with custom error handlers: I've created a custom error handler, which I initially set when my page loads : set_error_handler(array ( new ErrorHandler(), 'handleError' ));
It seems to catch all internal PHP errors, such as if I: var_dump($non_existing_var); right after the set_error_handler.... Now, I have an object that throws an exception after: set_error_handler(array ( new ErrorHandler(), 'handleError' )); $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception ... I thought that with an error handler set, I could 'skip' the try/catch for it, but doing so, PHP spits out in its internal log: PHP Fatal error: Uncaught CorbeauPerdu\i18n\LocaleException: ....
My error handler doesn't catch it at all before, thus my page breaks!! If I want it to go through the error handler, I have to init my Locale with a try/catch and use trigger_error() like so: set_error_handler(array ( new ErrorHandler(), 'handleError' )); try { $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception } catch(Exception $e) { trigger_error($e->getMessage(), E_USER_ERROR); } ... Is this normal ? I thought one of the goals of the error_handler was to catch anything that wasn't dealt with? Thanks for your answers! Hi I am implementing a read-only access to some specific attributes of a class via the magic __get method. I intend to raise an exception when trying to write to it using __set, but I'm not sure which exception is suitable to use. Is there any predefined exception to indicate such an error or should I just go ahead and define my own? |