PHP - Database Wrapper For Pdo With Proper Error Handling
Has anyone seen a decent database class for nicely wrapping up all the PDO functions? Ideally I'm after an example to handle database errors properly, insert/update/select queries, prepared statements and transactions. I've had a crack at writing my own and it's a bit messy with error handling everywhere. Maybe I need to put that in a separate class or something.
E.g. here's how I'd do a database update: $db = new Database(); // In page controller $params['type'] = $type; $params['details'] = $details; $query = 'insert into site_logs (type, details) values (:type, :details)'; $result = $db->preparedUpdate($query, $params); // returns false if error or # of rows if successful Just some examples would be great and I'll re-factor my one to make it better. Thanks! Similar TutorialsHello 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. Hello everyone, I've recently asked a question about forms and Requinix mentioned PRG method of processing forms. The PRG idea solves my refresh and back button document expired problems but i notice something new: when i refresh a page or use the browser back button - then return to the PRG process - repeat a refresh or back button action - i notice that i can traverse the cache history as many times as my prg approach redirects me. I feel like i am not implementing this PRG method correctly, or is this correct? Here is the form process if it helps solve the problem: i have a login form which contains a CSRF token. when i submit the form i specify an action as /prg/ which submits the data to index.php in the prg folder. After processing the data, prg index.php redirects to the root (because you are logged in). One problem is that i have a logo on the login page that allows you to return to the root (localhost index page). When the form is not submitted or it contaiuns incorrect login data or the logo is clicked to return to homepage, then the history seems to repeat itself. I've read that people recommend to use a header 303 See Other but the result is the same. Basiclly, if i am implementing a prg correctly, then the question becomes how can i instruct a browser to ignore the redirect as if the cache contains only the index page? i cannot find prg examples that involve a csrf token and other links on the protected page (prg/index.php protected because you need a form submission with a csrf token and it only processes data then redirects.) I don't see this happening in professional sites like Google or Microsoft etc. what am i doing wrong? 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)? 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 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. 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; } } } 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 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 My script displays results until I hit an error. I continually get fatal timeout errors that I am unable to handle or ignore. Yes I googled and found the custom error handler AND the simpler try/catch. Still cant figure it out... It has been 1 hour of playing with this without success so I have to ask . Please help. thanks : ) Code: [Select] try { if(($result=shell_exec("$commandLine")) == false) { echo "------>error"; throw new Exception; } else { echo "---->good"; } } catch (Exception $e) { echo "@@@__>exception caught"; } Hi. I'm trying to display all the missing fields (errors) when the user hits SUBMIT. My logic: IF there is NO EMAIL THAN add $errortrack array = $errormsg[EMAIL] IF there is NO OLDPASSWORD THAN add $errortrack array = $errormsg[OLDPASS] and so on. At the end, Print ALL the Error messages on the form using <?php foreach ( $errortrack as $key => $value) { echo "<dt>$key:</dt>"; } ?> The only thing it prints out is "0:" ever though there should be other errors. What am I missing? Site Link http://www.fusionfashionhair.com/newpassform.php My PHP Code: <?php session_start(); ?> <?php $submit = $_POST['submit']; // Form Data $email = $_POST['email']; $password_old = $_POST['password_old']; $password_new = $_POST['password_new']; $password_new_con = $_POST['password_new_con']; $errorcount = 0; $errormsg['Email'] = "Email Entered is Invalid"; $errormsg['OldPass'] = "Old Password Entered is Incorrect"; $errormsg['NewPass'] = "New Password Entered is Incorrect"; $errormsg['NewPassCon'] = "New Confirmed Password Entered is Incorrect"; $errormsg['SecCode'] = "Security Code is Incorrect"; $errormsg['NoErr'] = "No Errors, Continue"; $errortrack = array ($errormsg['NoErr']); if ($_POST[submit]){ if ($errorstop = "go") { $errorstop="go"; while ($errorstop<>"stop") { // check for existance if ($email) { echo "True - Continue 1"; echo "<p>----------</p>"; } else { $errortrack = array ($errormsg['Email']); $errorcount++; $errorstop="stop"; } // check for existance if ($password_old) { echo "True - Continue 2"; echo "<p>----------</p>"; } else { $errortrack = array ($errormsg['OldPass']); $errorcount++; $errorstop="stop"; } // check for existance if ($password_new) { echo "True - Continue 3"; echo "<p>----------</p>"; } else { $errortrack = array ($errormsg['NewPass']); $errorcount++; $errorstop="stop"; } // check for existance if ($password_new_con) { echo "True - Continue 4"; echo "<p>----------</p>"; } else { $errortrack = array ($errormsg['NewPassCon']); $errorcount++; $errorstop="stop"; } $errortrack = array ($errormsg="EVERYTHING IS OK"); $errorstop="stop"; }//End While Loop } else { while($errorcount>=0) { // Test display all error messages echo "<p>----------</p>"; echo "<p>Error Count = '$errorcount'</p>"; } die ("PLEASE FILL IN ALL FIELDS"); } } ?> My Form Code with the PRINT ERROR: Code: [Select] <form action='newpassform.php' method='post' id="regform"> <fieldset> <legend>Change Password</legend> <p><?php foreach ( $errortrack as $key => $value) { echo "<dt>$key:</dt>"; } ?></p> <p> <label for='email'>Email:</label> <input name='email' type='text' maxlength="25" value='<?php echo $email; ?>'/> </p> <p> <label for='password_old'>Old Password:</label> <input name='password_old' type='password' maxlength="32" /> </p> <p> <label for='password_new'>New Password:</label> <input name='password_new' type='password' maxlength="32"/> </p> <p> <label for='password_new_con'>Confirm Password:</label> <input name='password_new_con' type='password' maxlength="32"/> </p> <p><span class="required">*</span> Note, username and password are case sensitive</p> <p>Forgot your password? <a href="forgot_password.php">Click Here</a></p> <p>Login <a href="login.php">Here</a></p> <h2>Security Check</h2> <p>Enter letters below exactly how they are displayed. Letter are case sensitive. </p> <br /> <img src="captcha.class.php?usefile=1" /> <!--OR--> <!--<img src="image.php" />--> <input id='user_code' name='user_code' type='text' size='10' > <p> </p> <input class="reset" type='reset' value='Cancel' name='reset'> <input class="submit" type='submit' value='Continue' name='submit'> </fieldset> </form> <!--End of Form--> Hopefully there is a simple solution to this. I have a form that when submitted sends a message to an email address from the form. A customer fills it out, so there is no single one email address. However, half of the time, the retards that use this form dont know their own email address and dont bother to put the .net at the end of it. or they misspell it. The other half of the time they dont even bother to put the @ and the domain. They still think this is AOL for some god unknown reason. And I cant account for all the ways that they can not figure out how to fuck up their email address, so an email-validator doesnt work because they can even beat that and still manage to break it. For example, one guy named Mike continues to put the first half of his email in as Miek or Mik or just spelled completely wrong, and the 550 error that comes up when he puts that garbage in, which is most of the time (I think the guy is blind or something) is because his email address doesnt exist on the mail server because he cant spell it right, when on the off chance he actually does get the @domain.com in the end. I really hate my retard customers. So my simple little form blows up on them. But what I am trying to do is to have something like this if(@mail(args)) { //success, I'll call them back shortly } else { //youre a retard, please put in your email address correctly } However, the error handling isnt working. mail() is supposed to return FALSE if it encounters an error, an error that I'd rather put in an error log and not display to the customer, however, the error suppressor doesnt work. Any Suggestions? Hello, If I have an index file with: date_default_timezone_set('GMT'); error_reporting(E_ALL | E_STRICT); abstract class A { abstract public static function YesIReallyMeanAbstractStatic(); } class B extends A { public static function YesIReallyMeanAbstractStatic() { } } This will not error. However if I have: date_default_timezone_set('GMT'); error_reporting(E_ALL | E_STRICT); require('class_a_in_a_different_file.php'); // Or use __autoload() to do the same. class B extends A { public static function YesIReallyMeanAbstractStatic() { } } This will throw the error: "Static function A::YesIReallyMeanAbstractStatic() should not be abstract" I know abstract statics are debatable... but it makes no sense to me for it to be allowed in the first example but disallowed in other. So I was wondering if this is a bug? Or is there something else going on here? I assume the parser is evaluating the included file and then throwing the error which doesn't happen if both classes are in the same file as they can then be evaluated altogether. Hey guys i was wondering if someone could help or guide me. I have been messing around with php for quite some months now to the stage where i can code pretty much what i need to. but recently i started using paypals IPN and during testing i realised some problems arise for example when testing and people buying things say the payment failed due to a line not executing in your script for what ever reason, the person has lost their money yet you have gained it and they are lost. Take this code below for example: public function insertIntoDatabase($firstName,$lastName,$emailAddress,$merchant,$code,$database,$gameNumber) { $year = date("Y"); // Check what database we need to submit too:: $sql = "INSERT INTO playerGame (playerFirstName, playerLastName, playerEmailAddress, playerAccountType, playerCode, playerGameDate, playerGameNumber) VALUES (?,?,?,?,?,?,?)"; $stmt = $this->conn->prepare($sql); $stmt->bind_param('ssssssi',$firstName,$lastName,$emailAddress,$merchant,$code,$year,$gameNumber); $stmt->execute(); $stmt->close(); return true; } this is called on success the paypal IPN script. But what happens if this fails to execute? I suppose i could wrap it in a variable on the other side and test it if($task) { echo "code executed"; } but what happens if this fails ? of am i just being paranoid ? hope someone can help dont want to be ripping people off =] Thanks! 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 PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=351056.0 okay this sounds strange I know but but apart from html code in pure php the database values display correctly but when I combine with HTML code i get an offset error when retrieving certain values example results from database file no HTML coding: February10 2012 5pm MY EVENT NEW YORK ERROR when combined with HTML: February MYEVENT 2012 NewYork A friend of mine must of changed something on the site while I was asleep last night and now all the site says when you go to it is: Error Database query error Warning: mail() [function.mail]: SMTP server response: 530 SMTP authentication is required. in C:\xampp\htdocs\inc\utils.inc.php on line 449 I'm not exactly sure what he did since I can't contact him. Can anyone help me fix this? Hey guys, I am using this script to connect to mysql database. Here it is the code: <?php define('DB_HOST', 'localhost'); define('DB_USER', 'myusername'); define('DB_PASSWORD', 'mypassword'); define('DB_DATABASE', 'mydatabase'); session_start(); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } $login = clean($_GET['login']); $password = clean($_GET['password']); if($login == '') { $errmsg_arr[] = 'Login ID missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'PS ID missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); echo "ERROR"; exit(); } $qry="SELECT level FROM users WHERE login='$login' AND passwd='$password'"; if($result) { $result=mysql_query($qry); echo $result; exit(); }else { die("Query failed"); } ?> However, I have received an error which I catch from this line: echo "ERROR"; I have input the correct username, password and the name of the database. Do you have any idea why I have received an error, guess if I have missing something? Hi, I've uploaded my website to the server and I'm getting this error:- Code: [Select] Parse error: syntax error, unexpected T_VARIABLE in /home/c/h/chichesterag/public_html/Connections/gary.php on line 9 This is the first 9 lines of code:- Code: [Select] <?php session_start(); ?> <?php require_once('Connections/gary.php'); ?> <?php ini_set ("display_errors", "1"); error_reporting(E_ALL); $gary = mysql_connect("localhost", "root") or die("Error connecting to database<br /><br />".mysql_error()); mysql_select_db("people") or die("Error selecting database<br /><br />".mysql_error()); This is my connecting code:- Code: [Select] <?php # FileName="Connection_php_mysql.htm" # Type="MYSQL" # HTTP="true" $hostname_gary = "localhost"; $database_gary = "chichesterag"; $username_gary = "chichesterag"; $password_gary = "xxxxxx"; $gary = mysql_pconnect($hostname_localhost, $username_chichesterag, $password_xxxxxx) or trigger_error(mysql_error(),E_USER_ERROR); ?> The server's owner doesn't know what the problem is so I'm hoping someone here can help. Thanks, Gary Hi I am struggling to connect to my database and was wondering if someone could please help me. I am not sure what I need to put on line 10 in this code
<?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', ''); define('DB_NAME', 'tonyruttle'); define("PERPAGE", 10); $mydb = (DB_HOST, DB_USER, DB_PASS, DB_NAME); /*********************************************** ** SEARCH FOR MATCHING PRODUCTS ************************************************/ $showResults = 0; $search = ''; if (isset($_GET['srch'])) { $search = $_GET['srch']; $showResults = 1; $srch = array_filter(array_unique(explode(' ', trim($_GET['srch'])))); array_walk($srch, function(&$v, $k) { // add the +'s to the search tags $v = '+'.$v; }); $tagparam = join(' ', $srch); // // FINDTOTAL RECORDS IN SEARCH RESULTS // $params[] = $tagparam; $res = $db->prepare("SELECT COUNT(*) as tot FROM television p WHERE MATCH(title,keywords) AGAINST(? IN BOOLEAN MODE) "); $res->execute( $params ); $total = $res->fetchColumn(); $page = $_GET['page'] ?? 1; $params[] = ($page-1)*PERPAGE; // append parameters offset $params[] = PERPAGE; // and number of records for limit clause // // GET A PAGEFUL OF RECORDS // $sql = "SELECT id , title , active FROM television p WHERE MATCH(title,keywords) AGAINST(? IN BOOLEAN MODE) ORDER BY TITLE LIMIT ?,? "; $stmt = $db->prepare($sql); $stmt->execute($params); if ($stmt->rowCount()==0) { $results = "<h3>No matching records</h3>"; } else { $results = "<tr><th>Product Id</th><th>Title</th><th>Active</th><th colspan='2'>Action</th></tr>\n"; foreach ($stmt as $rec) { $cls = $rec['active']==0 ? "class='inactive'" : ''; $results .= "<tr $cls><td>{$rec['id']}</td><td>{$rec['title']}</td><td class='ca'>{$rec['active']}</td> <td class='ca'><a href='?action=edit&id={$rec['id']}'><img src='images/edit-icon.png' alt='edit'></a></td> </tr>\n"; } } } ?> <div id='title'>Product List</div> <form id='form1' "> <fieldset> <legend>Search titles and tags</legend> <input type='text' name='srch' id='srch' size='50' value='<?=$search?>' placeholder='Search for...' > <input type="hidden" name="page" id="page" value="1"> <input type="hidden" name="action" value="search"> <input type="submit" name="btnSub" value="Search"> </fieldset> <div id='formfoot'></div> </form> <?php if ($showResults) { ?> <div class="paginate_panel"> <?=page_selector($total, $page, PERPAGE)?> </div> <table border='1'> <?=$results?> </table> <?php } ?>
|