Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog. You can find information on programming, linux, documentation, tips for code and database optimization, my thoughts and rants, and whatever else I feel like sharing. Feel free to contribute to the blog by posting comments and asking questions.

Posts Tagged ‘php’

Calculating Sample Size in PHP

Posted by chris on December 13th, 2010 Comments(0)

How to return a sample size by population using PHP.

The formula is s = Z^2 * (p) * (1-p) / c^2 where , Z is the confidence level, and c is the confidence interval. Then:

ss = s / [1+(s-1 / pop)] where ss = sample size and pop = population size. Here is a simple PHP function I wrote the implements the formula.

function getSampleSize($pop){
	//$pop = 10000; // population
	$Z = 1.99; // confidence level
	$c = .03; // confidence interval
	$p = .5;
	$top = pow($Z,2)*($p)*(1-$p);
	$bot = pow($c,2);
	$ss = ($top/$bot);
	return round($ss/(1+($ss-1)/$pop));
}

I wrote this as a way to randomly sample a table  for errors.  We’ll see if it works.

Resources:

http://www.surveysystem.com/sscalc.htm

In Programming (, , , )

MySQL Temporary Tables Example – Optimizing PHP Applications

Posted by chris on November 24th, 2010 Comments (7)

Shortly after starting a new job as Web Application Developer with an e-commerce company I was tasked with rewriting a legacy application. After analyzing and flow charting the current application I found numerous performance penalties, bloated code, linear programming (non-OOP), and many other areas for optimization. Even after refactoring the code and removing these performance barriers the application was a bit sluggish. Though I had improved overall application execution time by 90% I still knew there was more I could do. This is where temporary tables came into play.

MySQL Temporary Tables have the same functionality as standard disk-based tables except they exist in memory. Since memory is not long term storage, they are temporary tables, hence the name. Operating in memory makes working with these tables fast, your only limit is the amount of memory/swap space available to you.

Read the rest of this entry »

In Programming, SQL (, , , , , )

What is PDO Error HY093: Debug/Fix MySql PHP PDO Error HY093

Posted by chris on August 11th, 2010 Comments (2)

I’ve been working with PDO at my new job and encountered this HY093 error. Infact that was the only information I received back from my PDO object. Usually there is a lot more information. My guess is that generally PDO is passing back the MySQL error directly from the MySQL server. However, HY093 is strictly an error issued by PDO.

In this case I received the HY093 error because I had improperly binded a data type to a variable.

I was using the form:

$db->prepare("SELECT * FROM tbl WHERE name = :name");
$pdo->bindValue(':name',$phpVar,PARAM_STR);
$pdo->execute();

Notice on line 2 I used “PARAM_STR” this should be PDO::PARAM_STR likewise had this been an integer it would have been PDO:PARAM_INT. Hopefully that helps some people.

Drop me a comment if this helped your or if you feel I missed something, thanks for reading.

In Programming, SQL (, , , )

How to Create a WordPress Plugin

Posted by chris on July 30th, 2010 Comment(1)

I recently had the opportunity to create a wordpress plugin for my company’s website. This is a simple plugin that associates blog posts to product pages on our shopping cart based on word press tags. The plugin simply displays links to the products page (based on the tags) on the wordpress post page for a given blog post.

First create a file in the wordpress plugins folder and add the following comments:

/*
Plugin Name: Article to Categories 
Plugin URI: http://www.foo.com/
Description: ...
Version: 1.0
Author: ...
Author URI: http://www.cnizz.com
License: ...
*/

WordPress will read in this information on the plugin page. Next we are going to hook into the core wordpress operations. Prior to this project I didn’t think much of wordpress. I viewed it as a great blogging platform with really horrid looking code, but the WP developers have a done a great job creating a really robust API. This hook will tell wordpress to call the show_category_pages_meta_box() function when it loads the admin menu. Now we need to define that function.

add_action('admin_menu','show_category_pages_meta_box');

This function defines a new meta box with an element ID of myplugin_sectionid. The title is Article to Categories and it will be displayed on post pages only. When loaded it will call show_category_pages() which will actually echo out the text to appear in the new meta box.

function show_category_pages_meta_box(){
	add_meta_box( 'myplugin_sectionid', 'Article to Categories', 'show_category_pages', 'post', 'side', 'high');
}

Finally we need to define show_category_pages() and populate our new meta box.

function show_category_pages(){
echo 'Some awesome product pages!';
}

Creating this wordpress plugin was pretty fun and I hope I get a change to do it again in the future.

Resources:
WordPress: Writing a Plugin
Plugin API
Action Reference

In Programming, Software (, , , )

Type Casting In PHP To Prevent XSS and SQL Injection

Posted by chris on March 14th, 2010 Comment(1)

Lots of developers think the best way to prevent XSS and SQL injection attacks are by passing all user input through a filter function. If you’re one of these developers don’t worry, you’re still right. There is a better (less code and less CPU cycles) way to do this on certain user inputs though. Type casting to integers should be used on all user inputs that should be a numeric value. This ensures that a valid data type is being used and it automatically converts any strings to an integer. This effectively prevents any SQL injection or XSS attacks.

1
$customer_id = (int) $_POST['customer_id'];

This automatically prevents someone from being able to pass in something like:

1
1' OR 1='1

or

1
window.location 'aol.evilcloneofaol.com'

It should be noted that when casting a variable to an integer there are limitations to just how big that integer can be. On 32-bit systems the limit is 2,147,483,647 and on 64-bit systems the limit is 9,223,372,036,854,775,807. I’ve hit the limit on 32-bit systems, but never on a 64-bit. When the variable you are casting to an int is too large PHP will always just return the highest number it can. Leading to lots of confusion when trying to debug this error.

PHP Reference on Integers

In Programming (, , , , )

How To Write a Page Controller in PHP for Dynamic Content

Posted by chris on February 6th, 2010 Comments (2)

This how to will cover the topic of creating a dynamic content system. It’s a well known fact that when you come across a site like wikipedia that they don’t have an html file for each article. That would be insanity. It would be nearly impossible to display the file tree in an IDE and cumbersome to search through even with an OS that has a slick file system and powerful shell like Linux. Trust me, I worked on a site that created a unique page for each product on their site (they’ve since gotten with the times). So how can web browsers access a page like http://en.wikipedia.org/wiki/Mike_Tyson, when that file doesn’t exist. The application uses a combination of server-side code, database storage, and apache htaccess magic. Here’s how to do this.

Apache HTACCESS
This is the most important part of redirecting dynamic content. The .htaccess file is what makes the magic happen. What happens is a user requests http://en.wikipedia.org/wiki/Mike_Tyson, apache goes to process the request and does its thing. Normally apache would redirect this to a 404 error page because the file does not exist, but if it see’s the .htaccess file in the directory, then apache will follow the rules we defined in the htaccess. Our rule will tell apache that if the file is not found, to go to some other file. We will call this file mycontroller.php (because its the controller in our ModelViewController). Below is some example code to get your started:

1
2
3
4
5
6
7
8
9
10
11
12
Options -Indexes
Options +FollowSymLinks
DirectoryIndex index.php
ErrorDocument 404 /404.php
 
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^(.*)$ mycontroller.php [L,QSA]
</IfModule>

Recap:
1. We have /public_html/mydomain.com/wiki/.htaccess
This overwrites the Apache Web Servers default operating procedures.

2. We redirect the request to /public_html/mydomain.com/wiki/mycontroller.php
This contains the server side code that will handle our request for the Mike Tyson article.

The Database
Going in detail on this topic is beyond the scope of this article, but you’ll need some sort of database management system to store your article on Mike Tyson and the thousands of other articles. Of course there are other options like an XML file, but a database such as MySQL is the sanest approach for most sites.

Server Side Code
You’ll need some sort of server-side code running whether is ASP, JSP, or PHP. I’m a bit partial to PHP so lets roll with that. In mycontroller.php your code might look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$uriArr = explode('/',$_SERVER['REQUEST_URI']); 
$article = $uriArr[2];
$article = urldecode($page); // in this case the article equates to Mike_Tyson
 
$sql = "SELECT * FROM article WHERE name = '$article'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1){
	$page = mysql_fetch_assoc($result);
	header('HTTP/1.1 200 OK');
	header('Connection: close');
	include_once 'mytemplatepage.php';
DIE():
}
else{
	header('HTTP/1.1 404 Not Found');
	header('location: /404.php');
	header('Connection: close');
DIE();
}

This is asking our database for any records it has on the request Mike_Tyson. If a row is returned than we know we’ve found our article. We tell the browser that this is a 200 OK request. Then we include a file called mytemplate.php (this file is never actually seen by the browser). We set the record in the database to a variable array called $page. Our mytemplate.php file will look for this variable and begin populating the article. Lets see $page contains the following data: Title, Body, Image, and References. The mytemplate.php file might look something like this:

1
2
3
4
5
6
7
8
9
10
$title = $page['title '];
$body = $page['body '];
$image = $page['image '];
$references = $page['references '];
echo "<html><head><title>$title</title></head><body>";
echo "<h1>$title</h1>";
echo "<div class="mainImage">$image</div>";
echo "<p>$body</p>";
echo "<p>$references</p>";
echo "</body></html>";

Sweet! We can use the same template for a bunch of different articles, without having to create multiple files. Now if the user had searched for the following url: http://en.wikipedia.org/wiki/Mike_TysonIsEvil, we wouldn’t have an article on that. So instead the code would tell the browser this is a 404 Error and route the browser to the 404.php page.

This is an over simplified version of a dynamic content system, but it would work. If I was developing one of these on a professional level it would be complete with objects to handle requests, string cleaners to protect against SQL injection and XSS attacks, error logging, and the works! Let me know if you have questions I can answer and thanks for reading.

Drop me a comment if this helped you out or have something to add, thanks for reading.

In Programming, Seo (, , , , , )

Using the GeoNames Web Service with PHP

Posted by chris on April 14th, 2009 Comments (2)

The GeoNames web service API, http://www.geonames.org/export/web-services.html, can be used to retrieve information on foreign countries such as postal code, city name, country code, longitude, and latitude. This information can come in very handy in variety of circumstances. I used the information obtained from the API to automate updating a table of countries with the postal code (just needed one in this instance) of every capital in the world.

First you will need to use cURL. I have written a simple cURL class:

Read the rest of this entry »

In Programming (, , , )

Dumping PHP Array Data and debug_print_backtrace

Posted by chris on March 17th, 2009 Comments(0)

By default you cannot write a print_r, var_dump, or debug_print_backtrace to a log in PHP. When you call these methods, PHP immediately echo’s out the data. Instead you must use PHPs ob_start which instructs PHP to not output anything from the script. To access the contents of the buffer use ob_get_contents and to let PHP know its okay to output from your script once again call ob_end_clean.

1
2
3
4
	ob_start();
	var_dump(debug_backtrace());
	$backtrace=ob_get_contents();
	ob_end_clean();
In Programming ()

Convert a PHP Object to an Array

Posted by chris on April 8th, 2008 Comments (8)

I’m really surprised that PHP 5 does not have built-in functionality for converting objects into arrays. Basically I had an Ajax function sending me a javascript object in JSON format to my PHP method. My method was already setup to handle an array, so after decoding the JSON into a PHP object and passed the object into this function.

1
2
3
4
5
6
7
8
9
	function objectToArray($object)
	{
		$array=array();
		foreach($object as $member=>$data)
		{
			$array[$member]=$data;
		}
		return $array;
	}

The problem with this method is that it will only move public variables into the array. Anything that is private cannot be accessed. You can try type casting your PHP 5 object to an array.

$array = (array) $this;

When I did this I got some really strange characters in the array. It does not seem that there is an easy way to convert a PHP 5 object to an array. Your best bet is to write a custom function that either converts your objects variables into array elements or if you are connecting to a database, just return the result set that builds the object in array form.

In Programming (, , )

Pass Objects and Arrays Between JavaScript and PHP with JSON

Posted by chris on March 13th, 2008 Comments (2)

In this article I gave a brief intro to using JSON to pass JavaScript arrays to PHP via Ajax. I’ve done a bit more with json since then and with the help of a co-worker discovered how to get javascript objects working together with php utilizing json.

Passing Multiple JavaScript objects to PHP

JavaScript class:

1
2
3
4
5
6
function product(id,name,price)
{
	this.id=id;
	this.name=name;
	this.price=price;
}

Above we just create a simple javascript class that we will call below.

Putting JavaScript objects into JavaScript array:

1
2
var object = new product('222','spectacular fizz','3.59')
var productsArr[productsArr.length] = object;

We can now add as many of the these objects as we would like to the products array. So lets say we have an array that looks like this below…

1
2
3
productsArr[0] = object...
productsArr[1] = object...
productsArr[2] = object...

…and we want to pass it over to PHP. So we use the following code to turn it into a JSON string.

1
var productsJSON = JSON.stringify(productsArr);

Now we need to do an AJAX Post and on the PHP side we decode the JSON string (note you only need to stripcslashes if magic quotes its turned on):

1
$productsArr = $this->json->decode(stripcslashes($productsJSON));

Now we can reference these objects multiple ways. One if we are just continuously looping through we can use a foreach:

1
2
3
4
5
6
foreach($productsArr  as $product)
{
	echo $product->id;
	echo $product->name;
	echo $product->price;
}

Or of course we can reference the object directly by its index in the array.

1
echo $productsArr[1]->name;

Pretty cool huh.

In JavaScript and Ajax, Programming (, , )