Updating old php scripts and learning PDO (PHP Data Object).

I started making websites in 1998. Gosh, in the internet years, that’s a forever ago. Remember Perl CGI and its cgi-bin folders? I have also written a lot of website using php along the way, and LAMP stack was sort of my thing for a while. But since I started to focus every efforts on front-end stuff, it have been a while since I looked at simple backends. Some of the sites that I created long ago desparaetly needs some updates. I have, in the past, thought or looked into converting sites to ruby on rails at one point, then looked into python, then thought hard about switching to some kind of static site generator engines (like jekyll or assemble.io), and finally more recently, thought about converting them to MEAN stack. But, really, who has time for that? Lately, I am thinking about just upping my php level and “patcing” it right in php5. Or at least keep the database structure and convert the backends to be more like API or services, still using php.

This weekend, I have been sort of playing with one of my old project: Softball Stats, written by David Carlo. It is an awesome little project.

“SoftballStats is a collection of PHP4 scripts and a MySQL database that track the stats, games, players, and every play made in multiple softball/baseball seasons. SoftballStats also compiles statistics for each player.”

I could use this on my work co-ed softball team, or also use it for my son’s summer league. I started updating it on my github.

Found this excellent website: phpbestpractices.org/

Here ares some notes that I kept while updating some of scripts.

First thing is the way I have been connecting to the database.

I was doing this:

$link = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT * FROM player WHERE SeasonID = 2014");
$row = mysql_fetch_assoc($result);
echo $row['name'];

New (Well, new to me.) way to do this is using PHP Data Object

$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$result = $pdo->query("SELECT * FROM player WHERE SeasonID = 2014");
$row = $result->fetch(PDO::FETCH_ASSOC);
echo $row['name'];

Also, way I was doing mysql_num_rows($result) will now have to changed to
$result->fetchColumn();

As with mysql_data_seek($result),

Simple enough? I was cruising along, then I encounter the error. Or more like, NOTHING. By default, error is a blank screen, as it turns out.

My php.ini was in /Applications/MAMP/bin/php/php5.5.10/conf/php.ini (Note that it is not MAMP/conf as you expect, it’s in /bin. you can find this infor using . and display_errors was in line 277.

Actually, you need to put those two lines in the php file:
error_reporting(E_ALL);
ini_set('display_errors', '1');

Got some things fixed, but broke more things. Ugh. Still working on it. Ah, time. I wish I had more.
Continue reading…


Random front end tips and tricks

I am learning tons this week. Very exciting. Working with smart people of Bocoup, learning/picking up tricks and tips on how to do many little “a-ha, that’s how you do it” things.

Here is my notes:

  • With Editor Config, you can create a project specific configfiles for your text editor of your choice. I am using sublime, and there is a package for that. Now we have a file on the project home that specify that we use tab for indentation for our project — that’s our style that we agreed on, and we are keeping it consistent — but I can start using two spaces for my other projects with this.
  • Bower is powerful. It’s managed by Twitter. Their stock is now at $40. Time to buy?
  • This gist by Matt Surabian is awesome. If you put it in your .bash_profile, your terminal shows your branch and with a * star if there is a change that needs commits. I use terminal with white backgroudn so I change like 38 to

    echo " on "$PURPLE$branch$dirty

    If you don’t want new line, get rid of \n from line 41.

  • I am learning about require js and Asynchronous Module Definition (AMD) API (Boy, do I have a lot to learn) but here are some example of diffrent types of AMD flavors by Tim Branyen and also, example of how to use it on multi page. I think I will start with Anonymous CJS style and see how it goes from here.

I’ve been posting links that I liked at Posterous (RIP) and then my tumblr blog. Here are the week worth of links:


Vagrant+Puppet is AMAZING!

vagrant-up

At my work on my team, we have five main developers. Two of us are on Mac, while the other three are on Windows. I, as a front end guy in the group, am advocating for SASS/Compass be used prominently on the redesign, like in depth use (great book btw). There is one little problem — workflow. To be able to developed locally, SCSS require pre-compiling, and it uses ruby. Mac comes with ruby, but Windows does not. Grunt could do it, but then you need node.js/npm. If I want everyone on my team to have it, I need to install all of those (ruby/sass/compass/node/npm/grunt)… that would be just way too much customization/potential places to break.

Enter Vagrant and puppet. It is just amazingly awesome. You can create a linux machine on VirtualBox – which is an open source VM. I am running latest puppet-enabled ubuntu box available from puppetlab, which is Ubuntu 13.10 (saucy Salamander).

Dealing with Vagrant really tickled my inner linux nerd-ness. Once upon a time, I was involved with running a group called BJLUG, Boston Japanese Linux Users Group — this was way back when, when you still had to pay for Apple’s CJK Language Pack to have Japanese installed on your machine, and I figured out that if you use linux, it was FREE to write email back to Japan etc. There were certainly a lot of LUGs back then. Not sure if they are around any more.

I learned how to install puppets, thanks to my colleague Kevin D. who patiently walked me through it, and was able to create box with apache and the likes.

Now we all need to download, and then just run vagrant up and vagrant provision. And your local scss changes, on your filesystem, using your favorite text editor on your OS, will be watched and css is compiled without any additional work. This is beautiful.

The Vagrant CLI documentation was useful for me, who have not used Vagrant before.

Some useful command:

  • vagrant up – Start the VM
  • vagrant provision – Provisions the VM
  • vagrant ssh – Logs into the VM with ssh
  • vagrant reload --provision – Restarts and provisions the VM
  • vagrant suspend and vagrat resume – If you don’t want fully shut the VM down
  • vagrant halt – Stops the VM
  • vagrant destroy – Deletes the VM

Actually, first time I saw use of vagrant was WordPress VIP team’s quick start. It includes all their server hosting environment. They do good work there over at VIP. And also there are ways to have local WordPress environment in vagrant such as Varying Vagrant Vagrants (VVV) environment. I am still using MAMP for my local wordpress theme/plugin development (when I have “free time”) but perhaps I should reconsider it. For new version of Daigo.org theme?
Continue reading…


Font awesome, and php split() to explode()

Couple of update notes

Noticed couple of things that I am doing over and over, and everytime I am doing it, i had to look it up (Thank you, Google for making us dumber and dumber…) thought to put it in a place for my future self…

Going from font-awesome 3.2.1 to the current 4.0.3

It used to be
<i class="icon-btc"></i>
but now you have to make it
<i class="fa fa-btc"></i>

PHP Split

split() is deprecated as of PHP 5.3.0. So if you want to convert something like 1974-05-25 into an array, an was using it, you can use explode() insted, like so:

list($Year,$Month,$Day) = explode('-',$info[dob]);
$stampeddob = mktime(12,0,0,$Month,$Day,$Year);
echo date("M. j, Y",$stampeddob); 


Emmet is AWESOME

emmet

While I thought it was great idea, I was not super crazy about HAML. Thanks to css and jquery, I always think DOM in css selectors. However, I just couldn’t stick with HAML. I liked to be able to code in html with < and >.

Meet Emmet.

Yes! Just like haml, you can write html with css selector, but you are coding in html. Let me show you what I mean. For example:

.row>.medium-3.small-6.columns.mycalss$*4>h3{Headline}+img[src="http://placehold.it/400x200"]+p>Lorem

Will produce

<div class="row">
	<div class="medium-3 small-6 columns mycalss1">
		<h3>Headline</h3>
		<img src="http://placehold.it/400x200" alt="">
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor, aspernatur ex magni magnam tempora hic accusantium expedita quia quaerat dolorum natus minima doloribus nostrum laboriosam autem ab voluptatum laborum maiores!</p>
	</div>
	<div class="medium-3 small-6 columns mycalss2">
		<h3>Headline</h3>
		<img src="http://placehold.it/400x200" alt="">
		<p>Ipsam, dolores, facere voluptatem deleniti at qui sunt! Facere magnam aspernatur eos adipisci doloremque vel explicabo magni! Tempore, quisquam, architecto, nulla facilis ducimus ex sequi porro nam mollitia placeat odio?</p>
	</div>
	<div class="medium-3 small-6 columns mycalss3">
		<h3>Headline</h3>
		<img src="http://placehold.it/400x200" alt="">
		<p>Quaerat, deserunt, odit eveniet impedit error quo necessitatibus tenetur ab sunt suscipit ipsam eligendi ea quibusdam! Error, modi, repellendus quos est doloribus temporibus ea sed voluptas reiciendis hic sunt assumenda.</p>
	</div>
	<div class="medium-3 small-6 columns mycalss4">
		<h3>Headline</h3>
		<img src="http://placehold.it/400x200" alt="">
		<p>Recusandae eligendi nisi ipsam nam. Assumenda, omnis reprehenderit distinctio illo at obcaecati nemo vitae magni iste enim molestias consequuntur debitis soluta eius sunt aspernatur ipsam sequi id sed maxime quos.</p>
	</div>
</div>

See the Pen plwIt by Daigo Fujiwara (@daigofuji) on CodePen

Amazing. $ for number, * to multiply, and lorem to put lorem ipsum in there. Awesome.

To install emmet on my sublime text 2, I have already had Package Manager installed on it, so all I had to do was run Package Control, which you could do by Menu > Tools > Command Pallete. Or hit Cmd+Shift+p. Type in install, select “Install Package.” Find Emmet, select. Done.

But what really sold me on Emmet was the “action” for comments. You can comment things with Command-/. Which works with both html and css (didn’t try with js, yet).

In css, m is margin, p is padding, bd for border, bg for background, etc. Great cheat sheet here.

Open a new file, save it as index.html, type ! and hit tab. Boom. HTML5 document is created. Crazy. I love it. Thanks Emmet!


Installing node and npm on my Mavericks MacBook Pro

npm-yo-grunt-bower

Package management is great. Yes, it is… WHEN IT WORKS. At least that was my attitude before.

As I anticipate release of Zurb Foundation 5 on November 21st, I couldn’t wait for it to go live. So, I decided to peak into their github branches. They are using Grunt in their process, and Foundation will be included in bowser. And documentation is built with Grunt using assemble.io. OK, those things are things that I have not have time to play with. I hear all the good things that node.js and its npm installed application can do… a lot of it like magic, they say. I just have never done it, partly because I was using Red Hat’s rpm when it went from Red Hat to Fedora and it stop working, and more recently, something went wrong with ruby version control RVM thing.

I am still a designer-turned-himself-into-developer, and even with all of my geekiness, still don’t quite understand, or still have a fear, about “computer science”.

Anyway. I decided that the time is now. Just do it.

So, here are my notes while I struggled through it all. I will likely have to do it again when I get a new computer or anything like that. I figured it would be good to leave trace.

Note: If you are here for “npm: command not found” problem, skip the middle part when I struggle with it and go to the end of the post for solution. It’s a permission issue and you need to run this: sudo chown -R $USER /usr/local
Continue reading…


Keeping your forked git repo in sync with its original

Git is awesome. I’ve been using reverie as a parent theme and my theme used here is a child theme.

Reverie is awesome. But since the theme is not installed through WordPress’s eco system, it doesn’t automatically get updated like some other themes. I noticed that the theme had update. I haev forked the theme to my repo, and wanted sync the changes.

Thank you stackoverflow. It suggested “adding a remote.” and found a great blog post about it: How to GitHub: Fork, Branch, Track, Squash and Pull Request on gun.io.

So here is what I did

$ git remote add --track master upstream git://github.com/milohuang/reverie.git

to add remote, then

$ git fetch upstream
remote: Counting objects: 16, done.
remote: Compressing objects: 100% (12/12), done.
remote: Total 13 (delta 5), reused 8 (delta 1)
Unpacking objects: 100% (13/13), done.
From git://github.com/milohuang/reverie
* [new branch] master -> upstream/master

Created a new branch upstream/master

$ git merge upstream/master
Updating 650455f..d442acb

—–

[UPDATE April 10, 2014]

I had to use this again and learned couple of new (for me) tricks. if you do

git remote -v

It will show you origin and upstream (if set).

Now, I can take this one more step and I can automatically deploy to my server when I commit to the git repo. A great blog post by How to deploy WordPress themes with Git.

I need to do this!


Memo: How to manage symlinks on mac

I’m developing WordPress themes using multiple repos (git and svn) and found that using symlinks to be the simplest way to manage it.

Here is my memo how I did what and how to check/re-do symlinks.

To create symlinks from from wp-config/themes

$ ln -s ../../../path/to/my/repo/mytheme mytheme

To check what is linked

$ ls -l
total 1
lrwxr-xr-x 1 daigo localhost Users 44 Oct 15 16:07 mytheme -> ../../../path/to/my/repo/mytheme

To remove the link
Didn’t know this, but looks like you can use both rm and unlink


Dreamhost.com hosted sites’ Cron Job failing? Maybe it’s cronlock…

Happend to me a couple times, and it is easy to fix but I always have to struggle, so leaving myself a note as well as parhaps helping people.

Good people at Dreamhost has made bunch of useful tools available, and one of the tool that I really like is the Cron Job, a simple UI that helps you write
Good people at Dreamhost has made bunch of useful tools available, and one of the tool that I really like is the Cron Jobs, a simple UI that helps you write otherwise pretty complex crontab. I am a big proponent of “automate boring things when possible, and spend time doing something that counts.”

For example, I have ste up a bunch of scheduled php scripts, mostly maintenance stuff. One day I got this error, and my php script was not excecuted:

setlock: fatal: unable to lock /tmp/cronlock.123456.78901: temporary failure

After some investigation and help from Dreamhost support, I found that this is caused by a tempoprarly lock file, which prevents parallel executions, was not removed after the excecution of the script for what ever reason. Fortunately, the owner of file is me, so I can delete it myself from command line.

Here is how:

  1. cronlock files are in /tmp folder, so ssh in, and cd /tmp
  2. Try listing cronlocks by typing ls -al cronlock*
  3. Find your username in that list, and notice that your locks (if there are multiple) all have common 6-digit numbers trailing cronlock, such as cronlock.1234456.78901
  4. run command rm cronlock.123456* (obviously, change the number)

and you should be all set. Hope this helps.


Introducing bbclub-font: Easily add Baseball club logos to your site/app. (my tweets: Sep 1-7)

Over the weekend, I participated in On Deck Cup hackathon (Submissions and winners, story by BostInno) and created bbclub-font: Easily add Baseball club logos to your site/app.

“bb” stands for “baseball” and in short, I created a web-friendly icon fonts of all 30 MLB teams.

bbclub-font-screen

I had a user story going in (So Agile!):

As a front-end developer, I want a easy way to put logos of MLB teams to the website/visualization so that I can easily enhance visuals on my database driven site/data visualization without much fuss

There are bunch of sabermetrics sites out there that offer bunch of really interesting contents. My hope is by creating this and open sourcing it, those sites can easily enhance their visuals as exciting as its contents.

Source is all viewable in my git hub repo

It is heavily influenced/inspired by two projects that I love and use,
StateFace by propublica and Boston-based Dave Gandy’s font-awesome

I’m pretty happy with the outcome. I pulled off what I wanted to accomplish in a time that was available. I did do a little bit of illustartor prep, (organizing logos into adobe illustrator format) but I did all the .ai to font conversion (using Glyphs Mini), css coding, writing and building a how-to documentation (github page using jekyll/foundation. Responsive, of course.) and building examples/demo within the hackathon time, beating the deadline!

As part of a demo, I used the Sports Data LLC’s API. It is really good. You can get an API key as trial and pretty much on the spot start using this. I think it is useful for baseballhackday in spring. I used Game Boxscore API to call in the day’s game, and deopending on the number of runs, changed the font-size of the logo. This was done in less than 2 hours (I had to skip *free* lunch, boo hoo) and I still need to work on it so that it’ll get more days than just that one (though I would be happy to imortalize the 13-9 win over Yanks.)

Creating font icon was something that I wanted to do for a while, but didn’t have time to execute. Now that I know how to do it, I feel can do this for my work going forward. What is nice is that all of those logos are in there and you can make them as large as you want, display resolution independent, retina ready, and it is only ~24k.

I used the app called Glyphs

I used the mini version which is only $44 and only support upper/lower case alphabets plus space (53 total) but the pro version is $300. If you are using it, I think it is money well spent imho.

***

I been tweeting nonsense since May 19, 2007 (such long time ago, can you believe that?). I put weekly digests of my tweets on this blog, so that I can search for it quicker using my blog’s search function. I tweet awfully a lot about baseball (I am a Red Sox fan, if you didn’t notice), but if you are interested, please follow me at @DaigoFuji. Here are my tweets between Sep 1 and Sep 7: Continue reading…