PHP - Handling Db Errors
Whats the best way to handle database errors.
I been using ob_start() stuff to run the code and if a database connection error occurs an variable $error turns to 1 and it displays the error code instead of the normal page that should be displayed when no errors occur. It works but I want to know if there is any better way to manage a db connection error while running a script. Also, how do you manage a problem when like 3 queries are ran to setup a new user account and the last one fails because the db connection drops or something, how would you go about handling a 2/3 query successful? I'm really stuck on how to manage errors if a db connection fails after the first connection is successful. Similar TutorialsThis doesn't work. Based off what I have seen online, it is suppose to. Basically, this is what I tried, and the quote is what was returned. I have no idea how to get this to work. It should have been pretty standard based off of the PHP documentation. The Xpath idea I got from someone else. Either way if I try to use find element by id or tag name it still returns an empty array, no matter what. Any advice on what I am doing wrong is appreciated. It doesn't matter what URL I try, none of them seem to work. Code: [Select] <?php $school_data = file_get_contents('http://www.infotechnologist.biz'); $doc = new DOMDocument(); $doc->validateOnParse = true; $doc->loadHTML($school_data); $xpath = new DOMXPath($doc); $tags = $xpath->query('div'); echo '<pre>'; print_r($tags); echo '</pre>'; ?> Quote DOMNodeList Object ( ) I have an application that loads several xml files, and then outputs some of the data from the file. The problem is that every once in a while, the service that provides the xml file does maintenance (or has an error in the file), and my application gives a "Fatal error: Call to a member function children() on a non-object in..."
I would like to handle the error differently, by displaying "unavailable" instead of the error. I know that this is usually not the appropriate way of handling errors, because there is a reason for a fatal error.
Any ideas on how to appropriately handle this error?
// Node 217 (GGB) $xml = simplexml_load_file("http://services.my511.org/traffic/API_KEY_REMOVED_FOR_EXAMPLE"); foreach($xml->children() as $traveltime) { $ggb = "$traveltime->currentTravelTime"; } echo "GGB:" , $ggb , " Minutes"; I am writing an API for clients to use to integrate with an server API I have written and it will be used in a variety of different environments and used by people with varying coding styles (hopefully), I was just wondering how I should handle errors? I was going to throw an exception, but what if people don't use a try / catch ? Should I return false to allow them to handle an error? private function _request($uri) { if ( ini_get('allow_url_fopen') ) { $this->_response = file_get_contents($uri); return false; } if ( function_exists('curl_init') ) { $ch = curl_init($uri); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $this->_response = curl_exec($ch); curl_close($ch); return false; } throw new Exception('Allow URL fopen disabled and cURL disabled'); } Also, any scenarios where the above would fail to return a result (apart from the obvious lol) Thanks, Andy Hi, I've inherited some html/php code (lucky me) and it's been years since i've played with it so I'm quite rusty. Anyway, I have a fairly bog standard login process and wish to simply display some text on the login page if the login detail is invalid and possibly log the error to a log file too. here's the index.php file...the login stuff is at the bottom Code: [Select] <?php $dir = dirname(__FILE__); require_once "$dir/ot/ot.php"; ot::include_view('header', array('account' => null)) ?> <html> <head> <title>Welcome to ....</title> </head> <body style="font-size: 14pt; font-family=verdana;"> <div><img src="OTLogo1.bmp"/><h1> Welcome to ...</h1> </div> <?php if (!empty($account)): ?> <div style="border-bottom: 1px dotted #AAA; padding-bottom: 2px; margin-bottom: 10px;"> <div style="float: left"> <?php $mtime = (int)@file_get_contents(otDB_DIR."/updated"); $date = date("d/m/Y", $mtime); $time = date("G:i", $mtime); if ($mtime > 0) { echo "Last Updated $date at $time"; } ?> </div> <div style="float: right">Welcome, <?php echo $account->email;?> - <a href="?page=home">Home</a> - <?php ot::include_view('logout_link')?></div> <div style="clear: both"></div> </div> <?php if (ot::is_admin()) { ot::include_view('admin_page'); } else { ot::include_view('user_page'); } ?> <?php else: ?> <p>Please login below.</p> <?php ot::include_view('login_form')?> <?php endif; ?> </body> </html> here's login_form.php Code: [Select] <form action='<?php echo $_SERVER['REQUEST_URI']?>' method='post' > <fieldset> <legend>Login</legend> <p>Email:<br/><input type='text' name='email' /></p> <p>Password:<br/><input type='password' name='pwd' /></p> <!-- <p><input type='submit' name='do_login' value='Login' /> <input type='submit' name='do_reset_password' value='Reset Password' /></p> --> <p><input type='submit' name='do_login' value='Login'/> </p> </fieldset> </form> and here's the function do_login (contained in ot.php..a php function file) Code: [Select] public static function do_login(&$err="") { $adb = ot::db('account'); $e = self::post('email'); $p = self::post('pwd', '', false); if (self::post('do_login') && $e && $p) { $ao = self::account_from('email', $e); if ($ao) { if (self::validate_login($e, $p, $ao)) { $_SESSION['id'] = $ao->id; return $ao; } } $err = "Invalid email or password"; return false; } } I'm unclear if the do_login fails as to how that ($err) is fed back to the web pages. Any assistance would be greatly appreciated. How do I display the actual errors in IIS 7.5? If I miss a semicolon, I get: "HTTP Error 500.0 - Internal Server Error" absolutely useless. In prior versions, I could see the line and get to the PHP error. How do I display PHP errors? I've added: set_ini('display_errors', '1'); but it doesn't help. Hello, Am writing a script that involves user input. Take an example: a user fills in a wrong username or password at the page login.php, my login processor (processor.php) detects it, how is the error "WRONG USERNAME OR PASSWORD" supposed to be transferred back to login.php. So far I have been using a session variable to transfer the error but am sure there is a better way to do this without displaying the error on processor.php itself. Thanx in advance Hey Guys,
Been coding PHP for a while but I always wonder about the right way of doing things. I am building an online community which I want to display to members and non-members. With this each screen will have options that are available for members only. I have set up session variables once a user logged in but its getting really old having to nest if statements on ISSET then again to check the values in the variables if it is set. See example below.
Question 1. Is it ok to session_start(); for all site visitors?
Question 2. If Q.1 is ok then is it ok to set all the session variables upfront with blank values as placeholders. This would eliminate the need for ISSET.
if (ISSET($_SESSION['On'])) { if (in_array($GroupID, $_SESSION['Groups'])) { $IsMember = 1; } else {$IsMember = 0;} } else {$IsMember = 0;}Just wanted to get your thoughts on this. Thank you, Jeremy Hi, I'm a beginner in PHP OOP and I'm with some doubts about the correct way of handling errors in PHP. Look at this function for example: public function deleteFileFromDisk($fileNameToBeDeleted) { $handle = unlink($fileNameToBeDeleted); if (!$handle) { $result = "(this->deleteFileFromDisk) - Error, " . $fileNameToBeDeleted . " not deleted."; } else { $result = "(this->deleteFileFromDisk) - Success, " . $fileNameToBeDeleted . " deleted."; } return $result; } Is this the correct way of doing it, or I can do better than this? Let me add some details of what I'm achieving... I'm running class methods, and I need to control errors in the process. If any call to the object throw an error I need to catch, stop all the process and send an e-mail with the error. Here are the object interactions: $testar_classe = new geoIpImportCSV('geolitecity', 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/'); $testar_classe->downloadAndSaveFile('./', $testar_classe->obtainDownloadFileName()); $testar_classe->uncompressZipFile($testar_classe->obtainDownloadFileName(), '.'); $testar_classe->deleteLine(1, 'GeoLiteCity-Location.csv'); $testar_classe->deleteLine(1, 'GeoLiteCity-Blocks.csv'); $testar_classe->deleteDataFromTable('tabela1'); $testar_classe->deleteDataFromTable('tabela2'); $testar_classe->insertLinesToDb('GeoLiteCity-Location.csv', 'tabela1'); $testar_classe->insertLinesToDb('GeoLiteCity-Blocks.csv', 'tabela2'); $testar_classe->deleteFileFromDisk($testar_classe->obtainDownloadFileName()); $testar_classe->deleteFileFromDisk('GeoLiteCity-Blocks.csv'); $testar_classe->deleteFileFromDisk('GeoLiteCity-Location.csv'); Which is the best way of handle this? Create a new method to take care of the exceptions? There are any examples on how to do this? Best Regards. I am inserting last names into the database using mysql_real_escape_string(), and outputting the data into a textbox using addslashes(). When I try to display O'Brian "O\" is displayed in the text box. The name is saved corretly as O'Brian in the database. I am printing the string like this: Code: [Select] echo "<input type='text' value='" . addslashes($customer['lName']) . "' blah blah..."; anybody have any ideas? Hi I'm completely new to error handling in PHP and wanted to ask whether I'm doing it right and, if not, what the right way would look like class DBConnection { public function execute($sql) { $query = @pg_query($this->dbconn, $this->prepare($sql)); try { if (!$query) { throw new DBException(); } } catch (DBException $e) { echo "Query execution failed"; exit; } } } I have set an SQL field as unique so that duplicates can't be entered, however rather then having the page error out and show the Error: Duplicate entry 'entry' for key 'field' I would like to be able to have a little div appear and say something like "this entry already exists" I already have it set to show that the item has been added but I have no idea were to start to make this work. Any ideas? Thanks, Jim Hello there, I'm having a problem displaying money correctly with php. I have a field called "balance" with the type float(10,2), in this field I have a number store as "34.55" which I can go in and look at within phpmyadmin but when I echo this value on the front-end of the site it is displayed as "34.549999237061" Can someone please help? Regards. I'm trying to develop a website file manager. I want to allow SSI, and would like to handle it specifically.. Code: [Select] $regexp = "<!--#include\s[^>]*virtual=(\"??)([^\" >]*?)\\1[^>]*\/-->"; if(preg_match_all("/$regexp/siU", $body, $matches, PREG_SET_ORDER)) { foreach($matches as $match) { $includeFile = $match[2]; } } This snippet shows how you would get the included file path in the SSI code of the website body [ the $body tag ], but I don't need to just find it- I want to replace the SSI code with a simpler code in the HTML that appears in the editor for easy management.. Then switch back from my easier code to the actual SSI code.. Example: Replace Code: [Select] <!--#include virtual="/newsManager/output.php"--> With Code: [Select] {INCLUDE=/newsManager/output.php} THEN when the user saves the page, Replace Code: [Select] {INCLUDE=/newsManager/output.php} With Code: [Select] <!--#include virtual="/newsManager/output.php"--> Is there an easy fix or should I just switch to a full blown template engine.. even though this is the only required feature? Hi, I have an HTML form created using Dreamweaver and now I need a script to handle the form processing. Basically what I need is for the form data received from the webpage to be organized in an email and then sent to me. I would also like to display a thank you message in the browser so the user knows it was received. I was planning to do this using CGI but a colleague suggested that CGI is old school and nowadays a developer would use PHP for this task. Is PHP the right solution for this project? The examples I have found so far always include the HTML for the form and the script needed to handle it in one file. In my case, I have an HTML form already in place and need it to work with a script to perform the email function. I know I need to set "Action=" on my webpage to point to the PHP script but what would the code look like if no HTML is needed? I hope this makes sense... Thanks for your help! Rob Hi ..am new to PHP and am using it to solve some mathematical problems which require extensive computation. Following is a code to solve a problem: Code: [Select] <?php $num =1; $n =0; $temp = 0; $count =0; $Final =0; While( $num < [color=orange]1000000)[/color] { $n = $num; while($n >1) { if(( $n % 2) == 0) { $n = $n/2; $temp++; } else { $n =3*$n +1; $temp++; } } If($temp > $count) { $count =$temp; $Final =$num; } $num++; $temp =0; } echo $Final; echo "<BR>"; echo $count; ?> I am running into "Maximum execution time of 30 seconds exceeded" error...its happening coz of the number 1 million...the code wrks fine for 100,1000,10000 and 100000...but breaks down @ 1000000.....is there any way to solve this situation...or PHP is not capable of handling huge numbers? please help...am stuck with this even though am so close to solving the prob. Thanks Abhijeet I have a prepared statement that returns an Article from my database. It then binds the results-set to variables. Most of the fields in the query are "required", so I *assume* that I am guaranteed to always get values back for those fields... Is that presumptuous? Here is a snippet of my code... // Execute query. mysqli_stmt_execute($stmt); // Store results. mysqli_stmt_store_result($stmt); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt)==1){ // Article was Found. $articleExists = TRUE; // Bind result-set to variables. mysqli_stmt_bind_result($stmt, $articleID, $title, $description, $keywords, $heading, $subHeading, $publishedOn, $author, $body, $referenceListing, $endnoteListing); // Fetch record. mysqli_stmt_fetch($stmt); // Close prepared statement. mysqli_stmt_close($stmt); // ???? Is it sufficient to have code like this... Code: [Select] <title><?php echo $title; ?></title> ...or do I need more error-handling?? Hope that makes sense?! Thanks, Debbie A form needs to get answers of math quiz, returning numbers, up to 2 digits after the point. In all form examples I noticed the usage of: Code: [Select] ...<input type="text" name="name" /... Cant it be a number? floating or integer? why "text" ? Also, can I limit the form to accept numerical input only or would I need to learn Ajax for that? Once I have the answer, I need to compare it to the correct answer. The method I have in mind is to multiply the answer and the correct one by 100 and compare the integer part. Is there a pre-made function that can do the same? Hi, i am php programmer , i need help from php expert to create php apllication for large database . I have database table called "profiles" which contains millions(1.5 to 2 million) of profile of the business companies. This table has 10 fields and there is one field named as "bname" which is name of company , i made this column full-text index for full-text search . Now , i have to use this table for profile searching (using full-text search), profiles within particular cities , profiles within particular categories etc. This table contains millions of records so it will take lots of time for searching and fetching the reocrd(s) from this table. Can anybody help me that how can i manage this large table to improve the performance and fast searching with php ? Is there any other technique (algorithm) to manage large database (like facebook,twiiter,orkut)? Not sure why the PHP variables in the code below aren't interpreting the values that they should be receiving from the HTML form. HTML form Code: [Select] <form action="handle_form.php" method="post"> <fieldset><legend>Enter your information in the form below</legend> <p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40" /></p> <p><b>Email Address:</b> <input type="text" name="email" size="40" maxlength="60" /></p> <p><b>Gender:</b> <input type="radio" name="gender" value="M" /> Male <input type="radio" name="gender" value="F" /> Female</p> <p><b>Age:</b> <select name="age"> <option value="0-29">Under 30</option> <option value="30-60">Between 30 and 60</option> <option value="60+">Over 60</option> </select> </p> <p><b>Comments:</b> <textarea name="comments" rows="3" cols="40"></textarea></p> </fieldset> <div align="center"><input type="submit" name="submit" value="Sumbit My Information" /></div> </form> PHP handle_form <?php #Script 2.2 handle_form.php $name = $_REQUEST['name']; $email = $_REQUEST['email']; $comments = $_REQUEST['comments']; echo "<p>Thank you, <b>$name</b>, for the following comments:<br /> <tt>$comments</tt></p> <p> We will reply to you at <i>$email</i>.</p>"; ?> Hello everyone, quick description of 'error handling' so that everyone understands the solution i am seeking. let php and the database handle the error is not an appropriate answer here. find out what i mean: using xampp, go to a login screen of your website, then turn off the database before submitting the login data. the connection will be attempted then fail. the browser will display its own error page which is white bg with a message. this is ridiculous. i made a custom handler that allows me to ignore this failure and show my own website with an error message. now how can i detect an error with a select or update statement? i am not a db designer, so i really don't know how to do it. what say i fetch filed['testmyerror'] and it doesn't exist or there is a problem. how do i write php code that is used to ignore this problem and display my own message. naturally i will log the error and/or log and send email to myself. anyone able to help? just a tip in the right direction? Thank you very much, i appreciate this forum and its members always. |