Archive

Posts Tagged ‘PHP’

An API for the Web: Learning YQL – Tuts+ Code Tutorial

Programming, Coding, & Development Interview Questions: Abstract Class Vs Interface in OOP

May 6, 2012 1 comment

Zemanta Puts Unwanted HTML Comments In Pre-Formatted PHP Code (Sourcecode) In WordPress Posts

April 9, 2012 4 comments

PROBLEM:

I  have recently determined through trial and error and process of elimination that Zemanta is responsible for adding extraneous HTML comments to my pre-formatted (with “pre” tags) PHP code that I have placed between “sourcecode” tags to activate WordPress.com’s built in programming code syntax highlighting.

Here is a screenshot (fig 1.) that demonstrates the problem:

codeslayer2010 blog with zemanta extraneous html comment errors

fig. 1

See, all that green is what commented my code out and made it so it doesn’t display correctly.

I am not totally sure Zemanta is to blame, but it seems the most likely culprit.  Here’s why:

  1. Identified 3 possible suspects: Zemanta, WordPress.com proofreading, and pasting pre-formatted code in Visual view instead of HTML view.
  2. Disabled Zemanta and retested –  problem remained.
  3. With Zemanta disabled, disabled proofreading as well.  No change.
  4. With Zemanta and proofreading disabled, went Edit>HTML View.  In each instance where I had posted code, deleted all the code from in between “sourcecode” tags.
  5. Re-copied and pasted code from each original PHP file.  Re-tested: Worked!  Syntax highlighting works properly now.  Made multiple edits to both code and text, updated and viewed the post — Good to go every time.
  6. Re-enabled Zemanta, made a test edit, saved and previewed the new post.  Everything is messed up again!  This is why I think Zemanta is the issue.

SOLUTION:

The solution I have come up with is this.

  1. If you want to use Zemanta, do so before adding any preformatted code or sourcecode tags.  Always turn Zemanta off when you are done using it.
  2. DO NOT, (under any circumstances) have Zemanta enabled if you have preformatted PHP code in your blog.  Chances are, Zemanta will mess your code up and you will have to re-paste your code again.  During my tests, I have had to paste all my sourcecode from scratch 3 times and let me tell you — it gets very tedious and wastes valueable time.
  3. Always paste sourcecode in HTML view only.

These are my recommendations based on my personal experience with this issue.  I’d love to hear from anyone else who is having similar issues.  Please let me know if this solution worked for you!

– CodeSlayer2010

Building A PHP Database Connection Class From Scratch (using Singleton & ActiveRecord patterns)

April 8, 2012 11 comments

EH_DESIGN_2012.04.03_PhpMySQLLogo_07Greetings folks.

Tonight I’m studying on how to create a PHP Object-Oriented MySQL database connection class.  This will be reusable and able to be implemented in any database driven web application built with PHP & MySQL.  It uses the ActiveRecord and Singleton design patterns.

I’m currently following this YouTube tutorial: Using OOP PHP to select, update, and insert data in a mysql database. Nick Huot really does a superb job of explaining step-by-step, not only what he is doing, but also why.

(24 hrs later …)

So I am pleased to tell you, dear reader, about the successful PHP OOP Database Connection class I built last night, based on Huot’s tutorials — they really are the best I’ve seen.

I had a lot of debugging to do, but that was simple.  Nick had not provided all the code for PHP validating of variables and such.  I’m sure he would have but he probably ran short on time, so no worries.  The validations I came up with (making sure rows had values and were of type array, for instance), I have provided for you below in hopes it will save some of you some time.  If you choose to implement my code examples you may find that there are still validations I had not accounted for.  I’d love to hear of any bugs that you find, or improvements that you make on this example, or on your own projects derived from this code.

COMPLETE WORKING EXAMPLE:

config.php

<?php  
   // Database Constants
   define("DB_HOST", "localhost");
   define("DB_USER", "root");
   define("DB_PASS", "[your_db_pass]");
   define("DB_NAME", "[your_db_name]");
?>
database.class.php

<?php
require_once('../../viewutilities.php');

class database
{
   private $host;
   private $user;
   private $pass;
   private $dbName;
   
   private static $instance;
   
   private $connection;
   private $results;
   private $numRows; // optional
   
   private function __construct()
   {      
   }
   
   // singleton pattern
   static function getInstance()
   {
      if(!self::$instance)
      {
         self::$instance = new self();
      }
      return self::$instance;
   }
   
   function connect($host, $user, $pass, $dbName)
   {
      $this->host = $host;
      $this->user = $user;
      $this->pass = $pass;
      $this->dbName = $dbName;
      
      $this->connection = mysqli_connect($this->host,
                                         $this->user,
                                         $this->pass,
                                         $this->dbName);
   }
   
   public function doQuery($sql)
   {      
      $this->results = mysqli_query($this->connection, $sql);
      
      if ($this->results && $this->results->num_rows > 0) {
                  
         // NOTE: The line below was giving me this error:
         // "Trying to get property of non-object"
         //$this->numRows = $this->results->num_rows;
         
         $this->numRows = $this->results->num_rows;

      } // end if
   }
   
   public function loadObjectList()
   {
      $obj = "No Results";
            
      if ($this->results)
      {
         $obj = mysqli_fetch_assoc($this->results);
      }
      return $obj;
   }
   
} // end class

?>
table.class.php

<?php
require_once('../../viewutilities.php');

/**
 * Uses Active Record design pattern to implement a class that
 *  closely matches a given database table.  This class contains
 *  methods for binding the class members and methods to CRUD
 *  database management principles.  This type of class is sometimes
 *  referred to a "Table Model", and in many designs it is implemented
 *  as an abstract base class, which is then extended and specialized
 *  as necessary.
 */
class table
{
   protected $id = null;
   protected $table = null;
   
   function __construct()
   {
      
   }   
   
   /**
    * Takes assoc array as param $data.  Dynamically creates class properties
    *  with key as property name and value as its value.
    *
    * @param array $data key value pairs
    * @return
    * @access
    */
   function bind($data)
   {
      //print_r($data);
      foreach ($data as $key=>$value)
      {
         $this->$key = $value;
         //echo $key."--".$value;
      }
   }
   
   function load($id)
   {
      $this->id = $id;
      $dbo = database::getInstance();
      $sql = $this->buildQuery('load');
      
      $dbo->doQuery($sql);

      $row = $dbo->loadObjectList();
      
      if (isset($row) && is_array($row))
      {
         foreach ($row as $key=>$value)
         {
            if ($key == "id")
            {
               continue;
            }
            $this->$key = $value;            
         }               
      }

   }
   
   // write database object contents to database
   function store()
   {
      $dbo = database::getInstance();
      $sql = $this->buildQuery('store');
      $dbo->doQuery($sql);
   }
   
   protected function buildQuery($task)
   {
      $sql = "";
      if ($task == "store")
      {
         // if no id value has been store in this object yet,
         //  add new record to the database, else just update the record.
         if ($this->id == "")
         {
            $keys = "";
            $values = "";
            $classVars = get_class_vars(get_class($this));
            $sql .= "INSERT INTO {$this->table}";
            
            foreach ($classVars as $key=>$value)
            {
               if ($key == "id" || $key == "table")
               {
                  continue;
               }
               
               $keys .= "{$key},";
               $values .= "{$value},";
            }
            
            // NOTE: all substr($keys, 0, -1) does is gets rid of the comma
            // at the on the last array element.
            $sql .= "(".substr($keys, 0, -1).") Values (".substr($values, 0, -1).")";
            
         }else{
            
            $classVars = get_class_vars(get_class($this));
            $sql .= "UPDATE {$this->table} SET ";
            foreach ($classVars as $key=>$value)
            {
               if ($key == "id" || $key == "table")
               {
                  continue;
               }
               
               $sql .= "{$key} = '{$this->$key}'";
               
            }
            $sql .= substr($sql, 0, -2)." WHERE id = {$this->id}";
            
         }         
      }
      elseif ($task == "load")
      {
         $sql = "SELECT * FROM {$this->table} WHERE id = '{$this->id}'";
      }
      return $sql;      
   }
   
   
} // end class

?>
user.class.php

<?php
class user extends table
{
   var $fname = null;
   var $lname = null;
   var $email = null;
   var $table = "user";
}
?>
index.php

<?php
include('./database.class.php');
include('./table.class.php');
include('./user.class.php');

require_once('../../viewutilities.php');

// this has my connection constants
include('./config.php');

$dbo = database::getInstance();
$dbo->connect(DB_HOST, DB_USER, DB_PASS, 'testpatterns');
//$dbo->connect('localhost', 'root', '', 'testPatterns');

$user = new user();
$user->load('1');

echo "Name of user 1: {$user->fname} {$user->lname}<br />";
?>

Now in the interest of time, I’m publishing this post.  Soon I will add commentary and explanations and such, however, experienced Object-Oriented PHP developers will understand how to code fits together without explantion.  The best I can do for the newbies for now is to say if your database exists, has data matching the format the class is looking for , and is running you should be able to put all these files in your PHP Apache web directory (I’m using WAMP and on my system it is in C:\wamp\www; on yours it may be different), and launch index.php to see a first and last name pulled from one row of data, specified by id number, in your MySQL database.

Good luck, and I’d love to hear from you if you have questions, comments, or issues that you ran into.

– CodeSlayer2010

P.S.: Go ahead and comment out the requires and includes for “viewutilities.php”. If you don’t, the code will not work because it will complain that it can’t find this file.

I left it in there because I will be publishing it later on and you may find it useful debugging tool for your PHP scripts. This class is a wrapper for print_r() function and there are all kinds of advantages, the least of which is one line of code vs three with all your pre-tag. But this class and it’s static “debug” method streamline and simplify debugging complex AMP-stack PHP-based web applications. Watch for it soon!

PHP View Utilities Code Debugger – A Wrapper For print_r function

Greetings folks.

If you’ve ever gotten tired of having to type:

echo "<pre>";
print_r($some_var);
echo "</pre>";

you are going to love the little debugger class I built. This is a very simple, basic class which doesn’t use patterns or anything fancy.  Actually, it may indeed use patterns that I’m not familiar with yet.  Nonetheless, in a nutshell it is a configurable, styleable wrapper for print_r.

The class is called ViewUtilities and it has one function in it — debug — which is a called as a static function.  The coolest feature about print_r is that you can put any variable type and it will faithfully show you that variable’s contents.  It is especially useful when viewing objects and arrays.  What ViewUtilities::debug does that print_r doesn’t already do is give you a way to easily differentiate which debug is which, when you use it in multiple places.  That differentiation is accomplished by a “styles” parameter that you pass when you invoke the function.

For instance, if you call the function this with a ‘2’ for the color scheme (third) parameter like this


ViewUtilities::debug($someVar,'$someVar', 2);

your output will be black text on a a light blue background as in fig 1.

*********** (fig. 1) … (screenshot here)

If you call the function with a color scheme value of ‘4’, on the other hand, your output will be charcoal text on a beige background as in figure 2.


ViewUtilities::debug($someVar,'$someVar', 4);

*********** (fig. 2) … (screenshot here)

…………….. The rest can go here …………….. too tired … will continue later. ……………
Blah … blah … blahh.

<?php

/**
 * $Rev: 4$
 * $Date: 2012-03-30 $
 * @author Eric Hepperle <eric.hepperle@bookit.com>
 * @date-created 2011-11-01
 * @description
 *  contains tools for developers to use in debugging and troubleshooting
 *
 * @version 4.0
 *
 */
class ViewUtilities {

    // CONSTANTS
    //
    const DS = DIRECTORY_SEPARATOR;

    /**
     * formats $var for pretty display using print_r()
     *  and echos the formatted result.  can be used anywhere you'd use print_r.
     *
     * @return string $out
	 *
     * @param mixed $var variable passed in.  can be any displayable type;
     *  basically same rules as print_r.
	 *
     * @param string $varName what you want to display as the variable being traced.
     *         note: there is no built-in function to return a passed argument
	 *				 name -- that is something I will investigate further.
	 *
	 * @version 1.2 Added ability to set color scheme and ability to document
	 *	what file a particular debug statement is located in. (02/13/12 - Eric)
	 * ------
	 * Color Schemes:
	 * 1 = black text, olive background
	 * 2 = black on light-blue
	 * 3 = light-gray on manilla
	 * 4 = charcoal on beige
	 * 5 = yellow on purple
	 * 6 = lightGray on manilla
	 * 7 = darkGreen on lightGray
     */
    public static function debug($var,$description='',$scheme='4') {

        $description = $description!=NULL && $description!='' ? $description : date("Y-m-d, g:i a");

		// names correspond to <background color>_<text color>
		$colorSchemes = array(
			'1'		=> 'background:#b9b91b;color:black;', // olive_black
			'2'		=> 'background:#c3d5fd;color:black;', // lightBlue_black
			'3'		=> 'background:#ffffc4;color:#888a85;', // manilla_lightGray
			'4'		=> 'background:#f5f5dc;color:#333333;', // beige_charcoal
			'5'		=> 'background:purple;color:yellow;', // purple_yellow
			'6'		=> 'background:#ffffc4;color:black;', // manilla_black
			'7'		=> 'background:lightGray:color:#006400;' // lightGray_darkGreen
		);

		// keep track of where our debug statements are
		$trace = debug_backtrace();

      //echo "<pre>\$trace: ";
      //print_r($trace[1]);
      //echo "</pre>";

      // if we have values keep them, otherwise set to empty - This is required
      //  to keep our output from throwing the "Undefined offset" error.
      $traceParam_file = isset($trace[1]['file']) ? $trace[1]['file'] : '' ;
      $traceParam_line = isset($trace[1]['line']) ? $trace[1]['line'] : '' ;
      $traceParam_function = isset($trace[1]['function']) ? $trace[1]['function'] : '' ;
      $traceParam_class = isset($trace[1]['class']) ? $trace[1]['class'] : '' ;

		$debugInfo = array(
			'file'			=> $traceParam_file,
			'line'			=> $traceParam_line,
			'function'		=> $traceParam_function,
			'class'			=> $traceParam_class,
			'debugApp'		=> __FILE__

		);

        // set style as yellow text on olive background
        $out  = "<div id='divDebug'
					style='$colorSchemes[$scheme];
							padding:10;
							margin:10;
							border-style:solid;
							border-width:2;
							border-color:red;
							word-wrap:break-word;'>";

		$out .= "<span style='color:#888a85;'>This Debug App is located in: <i>{$debugInfo['debugApp']}</i></span><br /><br />";
        $out .= "<span style='font-size:1.4em;font-weight:bold;'>DEBUG:</span>
				<span style='color:black;font-size:1.2em;'>{$description}</span>";

//        $out .= "<br /><b>CALLED BY:</b> " . __FILE__ . "<br />";

        $classParamInfo = '';

        if (!empty($traceParam_class) && class_exists($traceParam_class,false)) {

            $classParamInfo = "<li><b>Class:</b> <span style='color:red;font-style:italic;'>{$debugInfo['class']}</span><li>";

        }

		$out .= <<<OUT
			<div id='callerInfo' style='{$colorSchemes[$scheme]};
										font-family: arial, tahoma, sans-serif;
										width: 60%;
										padding: 10px;
										margin: 30px;

			'>
				<b><u>THIS DEBUG STATEMENT IS LOCATED IN:</u></b><br /><br />
				<ul style='list-style-type:none;'>
					<li><b>File:</b> <span style='color:red;font-style:italic;'>{$debugInfo['file']}</span></li>
					<li><b>Line:</b> <span style='color:red;font-style:italic;'>{$debugInfo['line']}</span></li>
					<li><b>Function:</b> <span style='color:red;font-style:italic;'>{$debugInfo['function']}</span><li>
               $classParamInfo
				</ul>
			</div>
OUT;
        $out .= "  <pre>";
        $out .= print_r($var,true);
        $out .= "</pre>";
        $out .= "</div>";

        echo $out;

    } // end function

} // end class

?>

Lynda.com PHP MySQL WAMP Project: Widget Corp – Progress Update – 2012.02.07

February 8, 2012 2 comments

Widget Corp tutorial progress (2012.02.07 - 1)

Hello folks.  I’ve been doing a Lynda.com tutorial called PHP With MySQL Essential Training.  I’ve actually been doing aboutg 2-8 hours per week of the multiple, sequential lessons that are involved in this excellent hands-on tutorial for about a month now.

At this point, I have completed all the basic PHP and MySQL material, and now in Chapter 13, I am creating a content management system from scratch.  I enjoy doing this video tutorial very much, though at times I have to pause to screen for 10 minutes or so to type in code manually from what’s on the screen.  When you subscribe to Lynda.com (around $30/mo) they have subscription options that provide you the example files to save you all the typing.  But, I firmly believe that, at least for me, as a relative newbie who is trying to understand all the mechanics of web application development with PHP & MySQL, the absolute best way to learn is to type everything manually.  In this way you basically link the code concepts together in your mind so that you can now type in various code modules by heart if need be.Image representing lynda.com as depicted in Cr...

At work we are using a Zend MVC-based framework, so I have practical experience in maintenance coding and creating small new features — mostly break-fixes though.  But I’m like a trained monkey — I don’t really know the mechanics and the logic of why to do things, only that somebody told me “if this, then that”.

I’m sure that sufficient for some coders, but sufficient isn’t good enough for me.  My goal is EXCELLENCE!  Therefore, I ask as many questions as I think I need to (after having already done as much research as I could on my own).  There’s no shame in my game.  After I get an answer I write it down in my journal and then I have my own “reference manual” that I can consult if I forget a step or need to recall that information down the road.  I have found that having new information written down actually results in a lesser likelihood of needing to refer to it in writing, and a greater incidence of ingraining in your brain by habit. I’m really happy with my progress on this project which I will refer to from now on as “Widget Corp”.  Basically, when it is all done I will have a highly refactored, efficient, and effective code template/framework for building customized CMS‘s.  I’m pretty psyched about having an actual “web application” that I can display to the world via my website. That image above is a screenshot showing what my app looks like in Firefox 3, locally on my Win XP machine.  Future improvements I intend to look into are:

  1. Figure out why it is bulleting blank lines.  (NOTE: I tried doing echo/exit in the code but no avail so far)
  2. Refactor to be Object Oriented.
  3. Refactor to use MVC.

Anyway. that’s all stuff down the road.  My goal for completion is March31, 2012.  Wish me luck!

Until next time, HAPPY CODING! 🙂

CodeSlayer2010

Testing WordPress’s Code Syntax Highlighting

December 4, 2011 1 comment

(12/04/11)

TEST 1:

This example introduces a bit of test code we are calling ‘CODE SNIPPET A’. It uses the ‘sourcecode’ tag and has no language attributes or parameters.

Code Snippet A

		<form id="form1">
			<div>
				<input id="btnShowMessage" type="button" value="show message" />
				<div id="divMessage" style="background-color: yellow;">THIS IS THE MESSAGE</div>
			</div>
		</form>
	

NOTE: When you are in your dashboard editing your post you will not be able to see the syntax highlighting. Don’t freak out. Do a save and ‘preview’ and everything should be just fine.

TEST 2:

This is snippet A except now we have added the language=’html’ attribute.

	<form id="form1">
		<div>
			<input id="btnShowMessage" type="button" value="show message" />
			<div id="divMessage" style="background-color: yellow;">THIS IS THE MESSAGE</div>
		</div>
	</form>

TEST 3:

Well that’s all good for plain old html. But, what if our code is from a scripting language, such as PHP, that alternates back and forth between html and the script code? In that case, you could use something like

	

Code Snippet B

	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
		<script type="text/javascript">
		  $(document).ready(function(){
			 nameOutput = jQuery('#nameOutput');
			 nameOutput.css({'background':'yellowgreen'});
			 jQuery('body').css({
				'background':'#A66900',
				'font-family':'comic sans ms',
			 });
			 nameOutput.wrap('<span style="color:purple;">');
			 jQuery('#wrap').addClass('centered');
			 jQuery('#wrap').css({
				'background':'#F2B449',
			 })
		  });
		</script>
		<style type="text/css">
		  /****** COLORS *******
			 #A66900 // brown
		   */
		  .centered {
			margin: 0 auto;
			width: 66%;
		  }
		</style>
	<div id="wrap">
		<?php echo "Welcome to " . 'hell'; ?>
		<br />
		<?php

		  echo "<pre>";
		  print_r($_SERVER);
		  echo "</pre>";

		  $model = new stdClass();
		  $model->smurf = 'Papa';
		  echo "my smurf = " . $model->smurf;

		  $model->_name = isset($_POST['userName']) ? $_POST['userName'] : '[not defined!]';
		  echo "<pre>";
		  print_r($model);
		  echo "</pre>";
		?>
		<H1>THIS PAGE IS CURRENTLY UNDER CONSTRUCTION AND TESTING</H1>

		<form id="main" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
		<input type="text" name="userName" value="Enter Your Name" />
		<input type="submit" name="submit" />

		<div id="nameOutput" name="nameOutput">
		  <?php if(isset($_POST['userName'])) echo stripslashes($_POST['userName']); ?>

		</div>
	<div id="content"></div>
	</div>