Country City Longitude Latitude Database setup in php

Ok, a nice Friday night here and I am working on a project that highly involves the geospatial data. For that I needed data comprising the info I needed.
Thankfully this website provided me the data as one big text file.

Then I wrote this simple snippet for porting the data to my kitchen database 😉
The script should be used only for temporary purpose and by no means on production. It doesn’t do any sanitation or what so ever the good programming.. but it does the job!
I created country_city table with the desired columns only;

CREATE TABLE `country_city` (
  `country_city_id` int(11) NOT NULL AUTO_INCREMENT,
  `country_code` char(2) NOT NULL,
  `city_name` varchar(100) DEFAULT NULL,
  `region` varchar(100) DEFAULT NULL,
  `latitude` float DEFAULT NULL,
  `longitude` float DEFAULT NULL,
  PRIMARY KEY (`country_city_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3170001 DEFAULT CHARSET=latin1

Then I run the following code to populate the data.

   <?php
   /**
    * @author Kaleb Woldearegay 
    * Code to be used "as is". Not responsible for any consequences after using the code.
    */
   const ROWS_TO_INSERT = 5000;
   $file_handle="/path/to/worldcitiespop.txt";
   $fh=fopen($file_handle, 'r');
   $query_pool=array();
   $db_handler=mysql_connect("localhost", "root", "");
   mysql_select_db("your database here");
   //assumed the database is connected at this moment..
   while(!feof($fh))
  {
      $line=fgets($fh, 1024);
      $data=explode(',', $line);
      $city=mysql_real_escape_string($data[1]);
      $query_pool[] = "(null, '{$data[0]}', '{$city}', '{$data[3]}', {$data[5]}, {$data[6]})";
      if (count($query_pool)>=ROWS_TO_INSERT)
      {
          $query = "INSERT INTO country_city VALUES " . implode(',', $query_pool);
          if (!mysql_query($query, $db_handler)) die('Error: '. mysql_error($db_handler));
          $query_pool=array();
      }
  }

That is it,
Enjoy!

The dist file “app/config/parameters.yml.dist” does not exist. Check your dist-file config or create it.

Are you upgrading symfony to 2.3. Bum! This will be the problem you would face after upgrading the composer.json file and trying to do 

composer.phar install 

the solution is simple. Just copy the existing parameters.yml file from app/config/ folder to new file called parameters.yml.dist and rerun the command

Single id is not allowed on composite primary key in entity Doctrine error

You might get the above error on PHP Doctrine

if you got the above error, then it means you have two or more ids as primary in your object representing the table.

Example:

class Member
   /** @id 
    * @Column(type="integer") 
    * @GeneratedValue(strategy="AUTO")
    */
   private $id;
   /** @id @Column(type="string") */
   private $key;
...

The above declaration would create the above error and taking out the generatedValue part can resolve the issue.

See the solution to common error of new entity was found though relation while using doctrine

How to automate http authentication url from php

if you have to download a file from a web address that would trigger a username and password window (http authentication), then here is the trick

$downloaded_content = file_get_contents("http[s]://yourusername:yourpassword@thefiledownloadurl");
file_put_contents('/tmp/tempholder.csv', $downloaded_content);

The line of interest would be the first one with file_get_contents.
Once you get the content, you can perform a lot of things, either use the content as it is, or copy it to file using file object or just simply transfer the content to other file as the example depicts..

Enabling PHP in Mac Mountain Lion

I have been using snow leopard and recently I got a new mac with mountain Lion. As a PHPer the first thing I was doing was to install php+mysql and I have found it much easier

here is how to enable apache for PHP:

1. go to terminal, click the launch icon from dock and you will find it in the utilities, and do
apachectrl start – you need a sudo access for this
2. Go to system preferences -> internet and wireless -> sharing and check web sharing
3. Now, go to http://localhost and verify the it works is there.
4. Then being on your editor, go to /etc/apache2 and open httpd.conf file. Then look for php5_module and uncomment that line.
5. You are done. For testing, go to /Library/Webserver/Documents/ and add a php file named phpinfo.php with content of phpinfo(); and access it from http://localhost/phpinfo.php

Happy PHP

Installing Imagick for php using pecl

If you are dealing with CAPTCHA or some graphics stuff you have definitely come across with Imagick.. it is a nice library that you should check out..
to install.. it is much really easy with pecl
here is the step by step process to install it..

pecl download imagick
tar -zxvf imagick-VERSION.NUMBER.GOES.HERE.tgz
cd imagick-VERSION.NUMBER.GOES.HERE
phpize
./configure --with-imagick=/opt/local
make
make install

Then, on successful make, you will see the path where the “dot so” is saved..
go to you php.ini file and add

extension=imagick.so

then restart you apache and check if the imagic is available on phpinfo()..

DONe!

Array Merging in PHP preserving keys. array_merge reindexing arrays

Merging arrays in php keeping the keys

Say you have two arrays with the following values in them:


$array1 = array(13=>'bad luck', 7=>'billion people');
$array2 = array(1=>'number');

And you want the final result to be


$final = (1=>'number', 13=>'billion people', 13=>'bad luck');

But when you merge arrays and using array_merge, u got the indexes being ripped out from the second or first array whose keys are numeric?

The result using array_merge would be

(0 => 'bad luck', 1 => 'billion people', 2 => 'number')

And you don’t want that

Here is a simple way – just use operator overloading of the plus sign

$array1 = array(13=>'bad luck', 7=>'billon population');
$array2 = array(1=>'number');
$merged = $array1 + array2;

Note: This is provided the keys are not overlapping, otherwise, the first array would take ownership of keeping the value.

Do you know how to run single phpunit test

Know who is calling your php script browser or script?

URL encoding in XSLT and php

want to url encode the value you are having in the xsl? do the follwoing two liner and you are done.

1. add the name space xmlns:php=”http://php.net/xsl on the xsl part first
2. then use php:functionString(‘urlencode’, “the text/node/orwhatever to be encoded here”);

DONE

was not found in the haystack error for select element in zend

You might get this error while working on zend form which has select element on it.

And most probably you are messing with this element on your controller or from your front end friend javascript [ that was in my case ]

Just put the following in the controller and you should be fine


$form->getElement('selectElementNameHere')->setRegisterInArrayValidator(FALSE);

This is a behavior of zend adding a default validator of inarray.
You would find more detailed explanation on zend website.

Learn node js angular and mongodb with simple step by step tutorials here

Fatal error: Using $this when not in object context in PHP

Whenever you got this error check the following:

1. Make sure the $this-> is used inside the object and referring to the class’s and inherited non-static members.

2. Make sure the called members of the object are properly addressed as static or member/function variables

Do you know the different different post types?

Here is an example for the second one.

Assume you have the following object


class Example
{
   function getExampleText()
   {
      return "Example Text";
   }
   static function getStaticExampleText()
   {
      return "Static Example Text";
   }
}

While accessing, if the code tries something like this one,

$example = new Example();
Example::getExampleText(); //Trying to access non-static as static

Then you would have the error