Create iPhone Apps with jQTouch

What is it?

jQTouch is a library for jQuery that has been optimized for iPhone and other mobile devices. It makes it really easy to make the jump from being a web developer to being a mobile app developer. I don’t really know Objective C and I really didn’t want to deal with learning it, but I wanted to make an app for my phone – just to build something quick to keep track of some stuff. I quickly found that jQTouch is the best platform for doing that if you’re a web developer.

There is something really cool about mobile app development on the web versus in an app store. There are some pretty distinct drawbacks too.  Here’s what I’ve found so far:

Continue reading

Automated Way to Find Google Pagerank

I was looking for an automated way to get Google Pagerank for a few hours and came up with quite a few things, but not many of them were very elegant.  Essentially, Google doesn’t provide an API and it’s against their terms of service to hit them up in an automated way.  I found quite a few places that have come up with close algorithms and calculate PR for sites, but that’s just not accurate enough for me.  The other option is to hit their PR URL that the toolbar uses.  For example:

http://toolbarqueries.google.com/search?client=navclient-auto&hl=en&ch=61470319184&ie=UTF-8&oe=UTF-8&features=Rank&q=info:http%3A%2F%2Fforums.digitalpoint.com%2Fshowthread.php%3Ft%3D164713

That returns the PR of Digital Point Forums, where I found that information, but you can’t change the reference URL, because of a checksum.  That’s the &ch= variable in the URL.  I’m working on a project that needs to look up PR on the fly though, so that just won’t work.  I ended up finding a script that I could use, but the guy didn’t put his URL in the comments, and I since can’t find it – oops.  I think he deserves a pat on the back though.  If this belongs to you, or you know who’s it is, let me know.

I tweaked the script and installed it on my Toolerific.com website.  Now you can go there and check the PR of any site without a captcha, which is nice.  The tool is here.

Now, the best automated way to check pagerank is to hit that site with cURL and take out the value of the HTML tag with the id “value”.  The reason that is the best automated way to do it is because Google may change their checksum rules and that will break the source code that I used to generate it, but that site will always be laid out like that, so you don’t have to worry about changing anything.  If you want the code I used, you can view it here.

Update: This doesn’t seem to work ALL of the time.  I suspect it has something to do with the checksum, but can’t figure it out.  Seems to be about 27% of the time, which isn’t great odds, but it works MOST of the time.  I’ll keep you posted if I find out more.

Paginating in MSSQL

I don’t really work with MSSQL very much and was wondering how to do pagination similar to doing it in MySQL with the LIMIT command.  It’s MUCH harder in MSSQL, but here is how you do it:

SELECT * FROM
 (SELECT TOP [size_of_record_set] * FROM
 (SELECT TOP [end_record] * FROM [table] ORDER BY [field] ASC) AS tbl1 ORDER BY [field] DESC
 ) AS tbl2

The Twitter API

I’ve been messing with the Twitter API for the first time in the last few hours, and I’ve learned a TON.  I know – I’m jumping on the bandwagon late, but oh well.  I managed to create a script to retweet “stuff” based on the search functionality and I made a script to automatically follow people that post specific things.  I also managed to get my account suspended in like 2 hours due to suspicious activity – whoops.  I guess you live, you learn.  Basically everything for status updates and following uses CURL, which looks a little something like this:

<?php
 $username = "<username>";
 $password = "<password>"; t t
 $message = "<message content>";
 $url = '<API URL>';
 $curl_handle = curl_init();
 curl_setopt($curl_handle, CURLOPT_URL, "$url");
 curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
 curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($curl_handle, CURLOPT_POST, 1);
 curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message");
 curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
 $buffer = curl_exec($curl_handle);
 curl_close($curl_handle);
?>

If you’re looking for more info on how to use twitter, check out this eSeries.  It’s a good resource.

So, have questions?  Let me know.  I’m hoping to do a twitter series soon!

Tidbit Tuesday on PHP: Simple MySQL Database Insert Function

This builds on a function I did last week: db_query(). You can send any array straight to a MySQL database and it’ll even check to make sure the column actually exists.  Oh, and it returns the id of the record you just added in case you needed it.

<?php
   function db_array_insert($cfg_array, $table, $array) {
      require_once("dbQuery.function");

      $sql = "show columns from ".$table
      $tableArray = db_query($cfg_array, $sql);
      $inputString = "";

      foreach($tableArray as $key => $value) {
         if (array_key_exists($value[0], $array) && $value[0])
            $inputString .= "'".addslashes($array[$value[0]])."', ";
         else
            $inputString .= "'', ";
      }

      $inputString = substr($inputString, 0, -2);
      $sql = "insert into $table values(".$inputString.")"
      db_query($cfg_array, $sql);

      return mysql_insert_id();
   }

   $insert_array = array(
      "column_1" => "something_1",
      "column_2" => "something_2"
   );

   $cfg_array = array(
      "db_loc" => 'www.databaselocation.com',
      "db_user" => 'some user'
      "db_pass" => 'some password'
      "db_name" => 'database_name_here'
   );

   db_array_insert($cfg_array, "some_table", $insert_array); //and use it.
?>

So what do you think?  Having a problem?  Just let me know in the comments.

Tidbit Tuesday on PHP: Simple MySQL Database Query Function

It’s always great to create functions for those things you do a lot.  Probably the single most common function I execute is database calls.

Here is a simple script for hitting up your MySQL database with a query:

<?php
   if(!function_exists(dbQuery)) {
      function db_query($cfg_array, $query) {
         $connection =
            mysql_connect(
               $cfg_array['db_loc'],$cfg_array['db_user'],$cfg_array['db_pass']
            ) or die(mysql_error());

         mysql_select_db($cfg_array['db_name'],$connection)
            or die(mysql_error()." >> ".$query);
         $result = mysql_query($query,$connection)
            or die (mysql_error()." >> ".$query);
         $i = 0;

         if($result != 1) {
            while ($data_array = mysql_fetch_array($result)) {
               foreach($data_array as $key => $value) {
                  $tableArray[$i][$key] = stripslashes($data_array[$key]);
               }

               $i++;
            }

            return $tableArray;
         }
      }
   }
?>

You should be able to just copy and paste this as a function and call it in one of two ways:

$cfg_array = array(
   "db_loc" => 'www.databaselocation.com',
   "db_user" => 'some user'
   "db_pass" => 'some password'
   "db_name" => 'database_name_here'
);

$query = "SELECT * FROM 'table' WHERE some_column = 'something'";

db_query($cfg_array, $query); // This will return an array with the table in it.

$query = "UPDATE/DELETE/ETC * FROM 'table' WHERE some_column = 'something'";

db_query($cfg_array, $query); // This will return return an empty array, but still works.

I use this function in EVERYTHING.  I also have some other functions that use this as its base.  Someday I’ll turn it into a class.

So, what do you think?

Tidbit Tuesday on PHP: Holiday Notices for Business Sites

This is a handy script for managing an out of office message on your website.  I find this very useful on business websites when you’re tired of making that one little change to let people know when the office will be shut down.  With about 15 minutes of extra work, you only need to do it once a year.

Let’s say for instance we’re doing all of the major U.S. Holidays in 2010, observing weekend Holidays with a day off on either side of the weekend.  This means first we need to determine what those dates are.  I just happen to have looked up the six most common, listed below:

  • New Year’s Eve – January 1st
  • Memorial Day – May 31st
  • Independence Day – July 5th (July 4th is Sunday)
  • Labor Day – September 6th
  • Thanksgiving – November 25th and 26th
  • Christmas – December 24th (December 25th is a Saturday)

Now that we know our dates, we can build them into an array:

$date_array = array(
   "New Yearís Eve" =>
      array("leaving" => "2010-12-31", "returning" => "2011-01-03"),
   "Memorial Day" =>
      array("leaving" => "2010-05-31", "returning" => "2010-06-01"),
   "Independence Day" => // July 4th is a Sunday
      array("leaving" => "2010-07-05", "returning" => "2010-07-06"),
   "Labor Day" =>
      array("leaving" => "2010-09-06", "returning" => "2010-09-07"),
   "Thanksgiving" =>
      array("leaving" => "2010-11-025", "returning" => "2010-11-029"),
   "Christmas" => // December 25th is a Saturday
      array("leaving" => "2010-12-24", "returning" => "2010-12-27"),
 );

The date array can easily be stored in a database or be made up of more complicated functions that would calculate the holidays across multiple years with some basic logic.  Maybe we’ll cover the latter part in another post some day.

Now we need to build the function itself.  This function will be run every time the page loads.  You can even include the function in a separate file to be included on multiple pages:

function holiday_message($date, $date_array) {
   $date = strtotime($date); // Reformat the date so we can do math on it.
   foreach($date_array as $key => $value) {
      $leaving = strtotime($value['leaving']);
      $returning = strtotime($value['returning']);
      $early_warning = $leaving - 86400 * 7;
      // If the date is between (7 days before) leaving and returning
         if($date > $early_warning && $date < $returning) {
            echo
               "We will be observing ".$key." from ".date("Y-m-d", $leaving).
               " until ". date("Y-m-d", $returning).".
               When we return we will be more than happy to assist you.";
         }
   }
}

Now we just need to execute this function anywhere on the page:

holiday_message(date("Y-m-d H:i:s"),$date_array);

This code can be customized in numerous different ways, so the the message is more formal, or works for your specific situation.  You can also change the way days are stored or calculated, like the example above.  This is a core to get you started.  Where can you go from here?

PHP Function Friday: date

I think the date function is extremely useful.  It gives your programs an awareness of WHEN they are.  You can do some pretty cool things like calculate this date from that date, make a calendar, or store information about when an action was taken.

Function and Syntax

string date(string $format  [, int $timestamp  ])

Manual Entry

http://php.net/manual/en/function.date.php

Notes and Use

There are two variables you can pass to the date function: the string format, and the timestamp.  What are those?  The string format uses various characters to define how the string the function returns will be formatted.  The table for which characters mean what is on the PHP Manual Page.  The timestamp is a Unix timestamp for a specific date/time.

Other Functions Referenced in Examples

Examples

Output Today’s Date and Time

This should just simply output today’s date.  I did a few formats based on January 1, 2009 at 4:52:39 PM.

echo date("Y-m-d H:i:s"); /* Should output '2009-01-01 16:52:39'.  Common programming format*/
echo date("F n, Y at g:m:s A") /* Should output 'January 1, 2009 at 4:52:39 PM'.*/

Put a Message on Your Website Every Monday

Do you hate Mondays?  Let everyone know.  This script checks to see if it’s Monday and then outputs a message if it is.  That ‘w’ in the date function is a numeric representation of the day of the week.  For instance: Wednesday is 3 and Sunday is 0.

if(date("w") == 1) {
   echo "Ugh.  It's Monday."
}

Examples Elsewhere on this Site:

Holiday Notices

Conclusion

Date functions are extremely useful when trying to figure out when you are (or better stated: when your program tries to figure out when it is).  Using date and time functions allow you to create a lot of automation in your scripts.  Have you got any useful implementations on this function?

PHP Function Friday: include

Including files makes it really easy to NOT duplicate code. It’s great for creating headers and footers for websites, or using it in the inverse: make the header and footer in one file, and include the content.  You can also store site configuration files, functions, and repeating content, etc.

Function and Syntax

include(<file path>);

Manual Entry

http://php.net/manual/en/function.include.php

Notes and Use

Includes are a great way to include the same code to many different PHP files.  I find this the most useful for storing variables and functions across an entire website.  The other great way to use this function is to include repetitive code that needs to be outside of a function scope – for example: including form layouts across multiple pages.  I like to use the same include for both my add and edit pages on a form sometimes.

Examples

Storing Site-Wide Variables

This is stored in the file ‘configuration.php’:

$blog_name = "jtGraphic.net";
$blog_description = "Ramblings of an Internet Addict";

This is another PHP file where you’re calling the include – call it whatever you want.  I’ll call mine ‘main.php’:

include("configuration.php");
echo $blog_name."<br />";
echo $blog_description;

This is another PHP file somewhere else on the site – maybe inside the /content/ directory.  Call it whatever you want.  I’ll call mine ‘content.php’:

include("../configuration.php");
echo $blog_name."<br />";
echo $blog_description;

Both ‘main.php’ and ‘content.php’ will echo out the same information because you included the same file at the beginning of each.

Website Header and Footer

I find that another extremely powerful use of includes is to build your header and footer for your website.  In this example, we’re going to dynamically set the title variable in the main content page and call it inside the include.  This is how I build some of my simpler sites.  By the way, this isn’t HTML standards compliant.  It’s just an example.

We’ll call this file ‘header.php’

<html>
   <head>
      <title>jtGraphic.net <?php echo $page_title; ?></title>
   </head>
   <body>
/*snip*/

We’ll call this next file ‘footer.php’;

//snip
      <div> &copy; James Thompson and jtGraphic.net </div>
   <body>
</html>

Now that we have our header and footer, we can make some more pages:

We’ll call this one ‘content_1.php’:

$page_title = "Some Title";
include("header.php");
//content here
include("footer.php");

We’ll call the next one ‘content_2.php’:

$page_title = "Some Other Title";
include("header.php");
//content here
include("footer.php");

When accessing ‘content_1.php’ and ‘content_2.php’ you should get everything you put in ‘header.php’ and ‘footer.php’, but the title should be what you defined in the content files.  This is a really rudimentary example, but it is VERY useful.

Conclusion

So, remember: whenever you have a set of code that is duplicated you can probably deal with it through custom functions or includes.  Don’t duplicate the code!  If you have your own examples, feel free to link them up below!

PHP Function Friday: function

So, I’ve decided to start including a new post every Friday – kind of as a discipline thing. I’m going to write a post on a PHP function every Friday. I’m not just going to regurgitate the post in the official PHP manual, but I’m going to list my experience with it along with some creative ways to use it.

With out any further adieu, I’m posting on the first official building block (which isn’t technically a function, but I digress) ‘function’:

PHP Function and Syntax

function <function name>(<parameters>) {
   /*add code here*/
}

PHP Manual Entry

Check here for version information, or anything I may have missed:

http://www.php.net/manual/en/functions.user-defined.php

Notes and Use

This is great for building blocks of code that you repeat a lot.  I like to use it when duplicating XML/HTML code, such as links or form elements, which I will outline below.  Functions, both custom and built in, are the primary building blocks of a good program.  Everything else is just procedural.

Also, on a side note: PHP Coding Standards is a good read if you’re really geeky.

An important thing to keep in mind about making custom functions is that someone has probably already made it if it doesn’t already exist in the built in functions for PHP.  Feel free to jump online and see if someone has already made a function to do what you’re trying to do.  I like to use the site HotScripts.com, which has both free and commercial PHP scripts available.  Chances are: if I need it, they have it.  It saves me a ton of time.

Note in the examples that I precede the function with some explanation of what it does, the author, etc.  This isn’t needed, but it’s a REALLY good habit.

Other Functions Referenced in Examples

Examples

Here’s the meat.  Let’s make some stuff work.

Creating Image Links

/*
 *  Author: James Thompson, jtGraphic.net
 *
 *  Description
 *  ------------------------------------
 *  This function is for displaying image links in HTML.  It's less typing,
 *  and easier to remember what needs to be slashed out.  An image
 *  with the same name as the file name of the page you're linking to needs to
 *  be placed on the server in the same path as the internal variable
 *  '$image_path' and the same extension as '$image_ext'.
 *
 *  Arguments
 *  ------------------------------------
 *  $url - URL of the link
 *  $extra_tag_html - this is any extra HTML, like class, id, or style
 *
 */

/* Build the function. */

	function create_html_link($name, $extra_tag_html) {
		/* Define internal variables. */
			$image_path = "images/";
			$image_ext   = ".jpg";

		/* Output the HTML. */
			echo
				"<a href="".$name.".php" ".$extra_tag_html.">
					<img src="".$image_path.$name.$image_ext."" />
				</a>";
	}

/* Execute the function. */

	create_html_link("home", "class="normal_link"");
	create_html_link("about", "class="normal_link"");
	create_html_link("contact", "class="normal_link"");

Calculate the Number of Days Since Some other Date

/*
 *  Author: James Thompson, jtGraphic.net
 *
 *  Description
 *  ------------------------------------
 *  Simple.  This calculates the number of days since X date.
 *
 *  Arguments
 *  ------------------------------------
 *  $date - the date in this format: 'YYYY-MM-DD HH:MM:SS'
 *
 */

/* Build the function. */

	function num_days_since($date) {
		/* Do some time math. */
			$date = strtotime($date);
			$now = time();
			$difference = $now - $date;
			$days = $difference / 86400;

		/* Output the Value. */
			return $days;
	}

/* Execute the function. */

	/* Should return 0 */
		echo num_days_since(date("Y-m-d H:i:s"));
	/* Someone's birthday at 6:02:55AM on Oct 23, 1974 */
		echo num_days_since("1974-10-23 06:02:55");
	/* Since Jan 1, 2009 - no need for time */
		echo num_days_since("2009-01-01");

Examples Elsewhere on this Site:

Holiday Notices

Conclusion

So that’s the basics.  Functions can be very powerful in reducing the code on your websites.  If you’d like to see some more custom functions, check out my Tidbit Tuesdays on PHP If you have questions, let me know in the comments.