Extract collections of similar objects from an array in php

A co-worker was working on some stuff dealing with creating collections of objects within an array so I decided to play around with the idea. Basically, you start with a big array filled of objects and the objective is to create smaller arrays of similar objects. In this case we want collections of person objects who names are the same. Here is what I came up with:

<?php

class person
{
	public $id = null;
	public $name = '';

	public function __construct($id, $name)
	{
		$this->id = $id;
		$this->name = $name;
	}
}

$persons = array();
$persons[] = new person(1, 'bob');
$persons[] = new person(2, 'bob');
$persons[] = new person(3, 'moses');
$persons[] = new person(4, 'joey');
$persons[] = new person(5, 'bob');
$persons[] = new person(6, 'joey');
$persons[] = new person(7, 'bob');
$persons[] = new person(8, 'moses');
$persons[] = new person(9, 'joey');
$persons[] = new person(10, 'joey');

$collections = array();

// loop until there are no person left in array
while(count($persons) > 0)
{
	// new collection and insert first person from array
	$collection = array();
	$collection[] = $persons[0];

	// now remove person from array since already in collection
	array_shift($persons);

	// loop through each person in array
	for($x = 0; $x < count($persons); $x++)
	{
		// check if there is a match
		if($persons[$x]->name == $collection[0]->name)
		{
			// add person to this collection
			$collection[] = $persons[$x];

			// pop if last item
			if($x+1-count($persons) == 0)
			{
				array_splice($persons, $x);
			}
			else
			{
				array_splice($persons, $x, $x+1-count($persons));
			}
			// move back since array position gets deleted, else will skip over next index
			$x--;
		}
	}
	$collections[] = $collection;
}

debug($collections);
function debug($o)
{
	echo '<pre>';
	print_r($o);
	echo '</pre>';
}

And the result is:

Array
(
    [0] => Array
        (
            [0] => person Object
                (
                    [id] => 1
                    [name] => bob
                )

            [1] => person Object
                (
                    [id] => 2
                    [name] => bob
                )

            [2] => person Object
                (
                    [id] => 5
                    [name] => bob
                )

            [3] => person Object
                (
                    [id] => 7
                    [name] => bob
                )

        )

    [1] => Array
        (
            [0] => person Object
                (
                    [id] => 3
                    [name] => moses
                )

            [1] => person Object
                (
                    [id] => 8
                    [name] => moses
                )

        )

    [2] => Array
        (
            [0] => person Object
                (
                    [id] => 4
                    [name] => joey
                )

            [1] => person Object
                (
                    [id] => 6
                    [name] => joey
                )

            [2] => person Object
                (
                    [id] => 9
                    [name] => joey
                )

            [3] => person Object
                (
                    [id] => 10
                    [name] => joey
                )

        )

)

You start with 1 big array and end up with, in this case, 3 arrays of person whos names are ‘bob’, then ‘moses’, and finally ‘joey’.

SQLSTATE[HY000]: General error – using php/pdo mysql stored procedures (sp)

I spent many hours last night trying to figure out why I was getting a fatal error: ‘SQLSTATE[HY000]: General error 0’ in my code and finally figured it out but first my environment. I’m using Zend Server CE running php 5.3.0, zend framework 1.9.0 and mysql 5.1.32. I should have tested this bug without the zend framework to make sure it’s not specific to zf (I don’t think it is) but I’m feeling lazy so I’ll let someone else try it out.

My code works as follows. I have a php class that calls a stored procedure which will take in an id, return a record set (if found) and will also return 2 out variables. While it was returning a record set everything was working perfectly fine. When I tried passing an invalid id, nothing was being returned and my code would keep giving me the ‘SQLSTATE[HY000]: General error 0’ (very helpful error indeed…).

The issue ended up being the way I had my stored procedure coded. I would first check to see if the id passed was valid, if so I would select the data else I would set my out vars to some value and do nothing else. For some reason, because I wasn’t returning a select, my code would blow up. In the mysql query browser, my stored procedure worked fine and my second select to get the out vars was working correctly. But php didn’t like it one bit. I tried forcing a select in my stored procedure in the invalid id section and then everything worked fine again. This sounds a bit confusing so here is the way I can replicate this. Continue reading “SQLSTATE[HY000]: General error – using php/pdo mysql stored procedures (sp)”

Creating RSVP in PHP/MySQL w/ Zend Framework

This post is to share the php/zend framework code I used to create an rsvp for my wedding site. I’m not going into all the details since that would take too long ;p but all the code is available if you want to use it. This was created using the zend framework version 1.7.

So I’m getting married in two month and for our wedding my fiancee and I decided to create a website for our guests. The site includes information such as location, time, links to registries, maps, and a section to rsvp. The site was made by my fiancee in html and css. When she was done, I ported it over to zend framework and started creating the rsvp section which I’ll describe next. You can view the finished wedding site here:

RSVP Page

http://www.joeyrivera.com/wedding

Continue reading “Creating RSVP in PHP/MySQL w/ Zend Framework”

Using MySQL Stored Procedure IN/OUT and Recordset w/ PHP

Note: The code below will not work on all environments. I’m using php 5.2.6 with mysql driver 5.0.18.

In a previous post:
http://www.joeyrivera.com/2009/using-mysql-stored-procedures-with-php-mysqlmysqlipdo/

I explained how to use MySQL stored procedures with different db adapters such as mysql, mysqli, and pdo in PHP. In those examples, I demonstrated calling a sp with in/out variables and calling a stored procedure that returns a recordset. One of the comments I received was a person asking how to call a stored procedure that uses in/out parameters as well as returns a recordset. It’s not much different and here’s how.

The trick is to combine both methods in one. Here’s an example of what the stored procedure looks like:

DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`get_users` $$
CREATE PROCEDURE `get_users`(
IN firstName VARCHAR(100),
OUT totalUsers INT
)
BEGIN
SELECT COUNT(*)
INTO totalUsers
FROM users
WHERE first_name = firstName;
SELECT *
FROM users
WHERE first_name = firstName;
END $$
DELIMITER ;

Continue reading “Using MySQL Stored Procedure IN/OUT and Recordset w/ PHP”

AMF,XMLRPC,JSON,REST Zend Web Services Tutorial

I’ve been using the Zend for the last few months and I’m loving it. Here at work we were having a discussion about implementing some web services in the future so I decided to see what it takes to create some web services in PHP using Zend. I was pleasantly surprise (well not really surprised) that it was extremely quick and easy to get things up and running.

In this post, I’m going to explain how to create web services that can be accessed via AMF, XMLRPC, JSON, and REST using the Zend Framework. Hopefully these should cover most uses out there. I left SOAP out since I don’t really see myself using it any time soon. I will be communicating with a database as well to make the tutorial more informative. The db will consist of one table with information about courses such as mathematics courses.

I’m going to show you the final product first, hopefully to catch your attention so you’ll read the rest :). This is what the final product will look like. If you look at the following links in Chrome, do a view source to see the formatted response.

XMLRPC

One course:  http://www.joeyrivera.com/ZendWebServices/xml-rpc/course-info/abbr/math101/
All courses:  http://www.joeyrivera.com/ZendWebServices/xml-rpc/courses-info/

JSON

One course:  http://www.joeyrivera.com/ZendWebServices/json/course-info/abbr/math101/
All courses: http://www.joeyrivera.com/ZendWebServices/json/courses-info/

REST

One course:  http://www.joeyrivera.com/ZendWebServices/rest/course-info/?method=getCourseInfo&abbr=math102
All courses:  http://www.joeyrivera.com/ZendWebServices/rest/courses-info/?method=getCoursesInfo

AMF

One course:  http://www.joeyrivera.com/ZendWebServices/amf/course-info/abbr/math101
All courses:  http://www.joeyrivera.com/ZendWebServices/amf/courses-info/ Continue reading “AMF,XMLRPC,JSON,REST Zend Web Services Tutorial”

Calling a DLL with PHP

So here’s a quick post on calling dll’s in Windows using php. I have a dll that encrypts data in a certain format that we need for another process. So I need to pass the dll a string and it returns the encrypted string back.

I tried calling the dll using the COM class in code and was having issues until I realized I have to register the dll in windows first before I can call it using the COM class. To register a dll in windows you do the following in your command line:

REGSVR32 MyStuff.dll

Now that the dll is registered you can do the following to start accessing the dll:

$my_dll = new COM('MyStuff.Functions');

MyStuff is the dll name an/or id and Functions is the object inside the dll that we want to use. Now I call the method I need and pass the parameters:

$encrypted_text = null;
$input = 'This needs to be encrypted.';
$my_dll->EncryptString($input, $encrypted_text );

This is pretty much it. We instantiate the COM class with the dll and function I want. Then I call the method in the dll passing my text and it returns into my $encrypted_text var the encrypted text. I can now do my next process with the encrypted text like:

print $encrypted_text;

Dynamic PHP Images Tutorial

So I decided to play around with creating a dynamic php image to see how much work was involved and it’s actually pretty easy to do. In my case I wanted to solve the following problem.

I have a trip planned for a weekend coming up and I keep wanting to see what the weather is going to be like for that weekend. It seems everyday the weather.com forecast changes so I keep checking it on a daily basis. My options are

  1. go to the weather.com website, search for the zip code, then select view 10 day forecast or 
  2. create a quick and easy automated way of looking for this information as a graphic. 

Of course, I picked the latter. Here’s what we are about to create:


Continue reading “Dynamic PHP Images Tutorial”

Using MySQL Stored Procedures with PHP mysql/mysqli/pdo

Wondering how to use stored procedures with PHP and MySQL? So was I and here’s what I’ve learned. In this tutorial I’ll explain how to use PHP (I’m using 5.2.6) to call MySQL (I’m using 5.0.2) stored procedures using the following database extensions:

First we need to setup our enviroment which consists of a new database with one table and two stored procedures. In your db tool of choice (I’ll be using the MySQL Query Browser) create a new database named test. After you create the new database, make sure to add a user called example with password example to the database and give it read access.

CREATE DATABASE `test`;

Now create the table users:

DROP TABLE IF EXISTS `test`.`users`;
CREATE TABLE  `test`.`users` (
`users_id` int(10) unsigned NOT NULL auto_increment,
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NOT NULL,
PRIMARY KEY  (`users_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Continue reading “Using MySQL Stored Procedures with PHP mysql/mysqli/pdo”

Random image from folder – rotating banner in php

So the other day someone was looking for a quick php script that would load a random image from a folder (rotating banner script) and display it on their website. There are already a ton of scripts out there that do this but of course, this was an excuse to build something for fun. So, I decided to create a script that would do just this but with the least amount of code lines still keeping it efficient (again, just for fun). This is what I came up with:

<?php
$files = @opendir($dir=trim($_REQUEST['dir'])) or die('Not Valid');
while($file = readdir($files)) preg_match('/(.png)|(.gif)|(.jpg)/i',$file) ?
        $images[] = array($file,substr($file,strlen($file)-3)) : null;
count($images) ? header('Content-type: image/'.$images[$id=rand(0,count($images)-1)][1]) :
        die('Not Valid');
print file_get_contents($dir.(substr($dir,strlen($dir)-1)!='/'?'/':null).$images[$id][0]);
?>

Continue reading “Random image from folder – rotating banner in php”

Getting list of members from an event in meetup.com with PHP

So, last week I attended our monthly Atlanta PHP meet and had a good time. At the end of the session some prizes were awarded “randomly”. Why “randomly”? Because a member of the group wrote down two names on a piece of paper and started asking the other members for a number. The two to get the numbers correct won an award. Now, this was a quick last minute thing for fun, so I am definitely over engineering this – but hey, that’s what makes programming fun!

The problems were:

  • (and I apologize for my honesty in case any member that attended the event reads this) I could see the persons hand movement while writing down the numbers so I already knew one of the numbers before starting. 
  • The paper was lifted at some point before he started calling out for numbers and I could see the second number written on the paper.
  • It’s not truly random

Continue reading “Getting list of members from an event in meetup.com with PHP”