Jump to content

Search the Community

Showing results for tags 'clean up'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome
    • Announcements & News
    • New Arrivals
  • Web Development
    • Programming
    • Database Development
    • Server Administration
    • Hosting & Domains
    • Frameworks
  • Web Design
    • HTML & CSS
    • Graphics & Multimedia
  • Desktop Discussion
    • Linux Development
    • Windows Development
    • Mac/Apple Development
    • Hardware Discussion
  • Marketing & Business
    • Advertising, Marketing, Monetization & Social Media
    • Search Engine Optimization & Traffic Building
    • Buy, Sell or Trade
  • Prodjex Web Development Applications, Tools and Plugins
    • IP.Board Applications and Plugins
    • Web Tools
  • The Developer Dump
    • General Chat

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests

Found 1 result

  1. PHP for all its sins is a very powerful tool. In terms of speed of productivity, nothing can touch it. Throw some code into a script, upload it and you are done! However this ease comes at a cost: what first appears to be "quick and easy" turns out to be an maintenance nightmare. Writing clean and robust code in PHP is hard. Often times, many newcomers do not always have a background in software engineering. This mixture of ease of use combined with no formal training in clean architecture can lead to "spaghetti code". This is one of the reasons PHP has gotten a bad reputation among professional developers. However with some effort and careful design, this does not have to be the case. In this short tutorial we shall look at writing clean and robust code that deals with databases. All web applications will have certain "settings", or "configurations". A bad approach is to copy and paste these settings all over the place! The clean approach is to place all settings and configurations into one file. This keeps things under control. When you need to make a configuration change, you no longer have to hunt you entire code base. So lets first create a "configuration" file: configuration.php: //================================== // config //================================== define("db_user", "user"); define("db_pass", "password"); define("db_name", "demo"); define("db_server", "127.0.0.1"); Now connection to a database in php is very common, however the code is quite a lot of boiler plate. Also when parameters are used for sql queries these need to be carefully "escaped" to avoid nasty security attacks such as "sql injections" By creating functions, we can encapsulate the core database access functions. This will reduce the code and also make it very clean. The sample below shows the data access functions: data_access.php: //================================== // Data Access //================================== function runSQL($Query) { //connect to server, then test for failure if(!($conn = mysql_connect(db_server,db_user,db_pass))) { print("Failed to connect to database!<br>\n"); exit(); } //select database, then test for failure if(!($dbResult = mysql_query("USE ".db_name, $conn))) { print("Can't use the database.<br>\n"); exit(); } $rs = mysql_query($Query) or die(mysql_error()); mysql_close($conn); return $rs; } function runSQLParms($Query,$Params) { //connect to server, then test for failure if(!($conn = mysql_connect(db_server,db_user,db_pass))) { print("Failed to connect to database!<br>\n"); exit(); } //select database, then test for failure if(!($dbResult = mysql_query("USE ".db_name, $conn))) { print("Can't use the database.<br>\n"); exit(); } foreach($Params as $key => $value) { $Query = str_replace($key,mysql_real_escape_string($value,$conn),$Query); } //echo $Query; $rs = mysql_query($Query) or die(mysql_error()); mysql_close(); return $rs; } In the above data access functions, we have two main functions runSQL and runSQLParms. These two functions are now ready to be used in your projects to cleanly access data. Example: Imagine we have a php file where we are required to do various database actions. First we need know we need the database "configurations" and also our database access functions. Lets import them at the start of the file: sample.php: require_once("configuration.php"); require_once("data_access.php"); Lets say we need to flush some data from a temporary table (we need to execute some sql): function FlushTemporaryData() { $sql = "delete from temp_table"; runSQL($sql); } What if we needed to delete a particular record between say a date range? We would require sql that has parameters. Usually these parameters would be values passed from client side forms. When accepting data from users, there is always a danger of "sql injections". We can safely do it using the second database access function: function DeleteUserLog($UserId, $Start_Date, $End_Date) { $sql = "delete from user_logs where userId = @UserId and log_date between @Start_Date and @End_Date"; $p["@UserId"] = $UserId; $p["@Start_Date"] = $Start_Date; $p["@End_Date"] = $End_Date; runSQLParms($sql, $p); } As you can see the runSQLParms function requires two things: The SQL query, and an array of Parameters. The function will automatically take each parameter and merge it into the SQL query. Also each parameter will be escaped to stop sql injections. Of course, we will often require to get some data back and do things with the result (such as render it as html). lets image we would like to display the top 5 students based on their score: function DisplayTopStudents() { $sql = "select First_Name, Last_Name, Score order by Score desc limit 5;"; $rs = runSQL($sql); $html = ""; while($row = mysql_fetch_array($rs)) { $html = $html . $row["First_Name"] . " " . $row["Last_Name"] . "Score:" . $row["Score"] . "<br/>"; } echo $html; } This is just the tip of the "iceberg". Hopefully you can see how easy it would be to create and maintain these functions. Questions and feedback welcome!
×