Pats Over Bills 20-10

Bills fall to New Englad 20-10

And that’s how you win a football game.

~A!

Easier Javascript Form Validation

I was racking my brain trying to find the best way to do form validation across a huge application, and I knew what I wanted to do. I wanted to implement a single function I could use to validate every form, without needing to resort to all kinds of manual coding.

I decided to use the class attribute for a little more than formatting. It's an ideal space to use for ad-hoc properties, since it allows as many class names as you want to put into a single tag.

Here's a basic form:

HTML:
  1. <form name='myForm' id='myForm' method='post' onsubmit='validate(this);'>
  2.   Name: <input type='text' class='required' name='name' />
  3.   Address: <input type='text' class='min20' name='address' />
  4. </form>

Notice the class names above. I've used 'required' as the class for the first input, and 'min20' for the second. I want required to mean the field cannot be blank, and I want min20 to mean the field must contain at least 20 characters in order to be valid.

Here is the validate function, which takes a form object as a parameter:

JavaScript:
  1. function validate(frm) {
  2.   var elms = frm.elements;
  3.   var numElms = elms.length;
  4.  
  5.   for (var i = 0; i <numElms; ++i) {
  6.     if ( (/required/).test(elms[i].className) && !elms[i].value) {
  7.       elms[i].focus();
  8.       alert('You need to fill in this field to continue...');
  9.       return false;
  10.     }
  11.  
  12.     if ( (/min20/).test(elms[i].className) && elms[i].value.length <20) {
  13.       elms[i].focus();
  14.       alert('This field requires at least 20 characters in order to continue.');
  15.       return false;
  16.     }
  17. }

Now, those error messages suck. You'll want to do better, possibly using the name of the element, or the title attribute, or something else that will help it be more descriptive. That's outside the scope of this post, I'm just showing the mechanism for validation, bells and whistles on it are up to you.

~A!

Two Helpful Pipes

Two quick tips tonight, both linu/unix command line devices I worked out trying to implement different utilities without writing code.

The first is a mysql database copy using the tools available from the default mysql commands:


mysqldump -u USERNAME -pPASSWORD -h HOSTNAME DBNAME |
mysql -u USERNAME2 -pPASSWORD2 -h HOSTNAME2 DBNAME2

Like most of the useful things in the world, it is simple to the point of idiocy. So simple, in fact, that I almost wrote a PHP script to log in, pull the data, then source it into the second db.

The first part of the command above does a basic MySQL dump on DBNAME. It streams that dump to the second part of the command after the pipe, which sources the commands in a batch, as if you had run the mysql command with an input script:


mysql -u USERNAME -P PASSWORD .... < inputfile.sql

The second one I was having some fun with was streaming out to gzip with the same basic mechanism:


cmd ... | gzip -9 > out.gz

which takes the output of any command, gzips it, and stuffs it in out.gz . This is actually the handier of the two for the work I do from day to day, which involves a lot of database backups and such.

That's all, just some quick points, wanted to check in and write _something_ at least.

~A!

Q&A Selecting in a Listbox after submit

This question was submitted on February 4th, 2008:

Hi,
I have a combo box called "A" which contains fruits and vegetables
and a list box called Types(i.e) which will display the corresponding types(Eg if we select Fruits then it will display apple, mango and if we select vegetable then it will display carrot, onion etc.
Based upon the selection in the list box and on clicking submit button it will populate the table which will containe prices.
On First loading the page both the combo box and list box will contain "select" as first option. Then we choose Fruits and their corresponding types listed in the List box and based on the selection in the list box and after clicking submit button the table gets populated. All the values are updated in the database.
On Reloading the page we should get the same value which we have selected in Combo Box "A" and list box "Types" and table also should be populated. I am getting the List box value from the database and i am iterating with the list of values in List box.
Eg If i selected Mango and then clicked submit button and same is updated in database.So while i am reloading the
page i am comparing mango with apple, pineapple, mango,custard apple etc. If a match is found i am highlighting that value and the corresponding table should be displayed
The problem here is combo box value and list box value is first displayed and then it takes few seconds to display the Table which looks very awkward for the end user.
Below is the coding which i have done....

JavaScript:
  1. for(optionId=0, key=1, value=0; optionId <maxEntityCount; optionId++){
  2.  document.form1.listbox.options[optionId] = new Option(fruitsArray[key],fruitsArray[value]);
  3.   if(typesoffruits == fruitsArray[key])[html]
  4.   {
  5.     document.form1.listbox.options[optionId].selected = true;
  6.     isSelected = true
  7.   }
  8.   value=value+2;
  9.   key=key+2;
  10. }
  11.  
  12. if(isSelected == true){
  13.   loadtable();
  14. }

I want to know whether there is any way in java script such that without iterating the loop i should able to highlight the value which i got from database and the corresponding table should be loaded. That is without iterating typesoffruits with fruitsArray i must able to highlight the typesoffruits and its table should be displayed.

Thanks for patiently reading such a long mail..
Thanks for your efforts and response.[/html]

What it sounds like you're looking for here is actually pretty simple to accomplish. You're keying on the key here, and if you've got the relationship set up the same way in the select element, you can very easily set them to be selected with the following code:

JavaScript:
  1. /*
  2.    if "mango" is selected, and has an id of 1, we assume
  3.    that the option in the list box is going to look like this:
  4.    <option value="1">Mango</option>
  5.   */
  6.   var elm = document.forms['form1']['listbox'];
  7.   elm.options[1].select = true;

Keep in mind, however, that in order for this to work, you must have the elements in the select element ordered by the key, and not alphabetically.

So you'd need to have:

HTML:
  1. <select name="listbox">
  2.   <option value="0">Select</option>
  3.   <option value="1">Mango</option>
  4.   etc...
  5. </select>

Without more information, that's the best answer I can provide. If you'd like to submit the code for review and adjustment, please feel free.

Comments always welcome!
Anthony

Followup 2/5/2008:

Thanks Anthony for you very valuable suggestion and help. That code is working fine. I am having one more query ...
How can i get the multiple selected values from lIst box using Java script.

Example: Consider i have mango, apple, grapes,strawberry in a listbox.
I am selecting apple and grapes and on click of submit button I am calling a javascript method called getFruits(). In that method, how can i get the selected values i.e(apple and grapes).

Thanks and Regards

This is fairly simple as well. Hat tip goes to DigitialAmit.com, where I picked up this nifty little snippet that does precisely what you need.

JavaScript:
  1. var arSelected = [];
  2.  
  3. function getMultiple(ob) {
  4.   while (ob.selectedIndex != -1) {
  5.     if (ob.selectedIndex != 0) {
  6.       arSelected.push(ob.options[ob.selectedIndex].value);
  7.     }
  8.      ob.options[ob.selectedIndex].selected = false;
  9.    } // You can use the arSelected array for further processing.
  10. }

Which will get all of the selected items and then deselect them. If you wanted to re-select them after you did the collection, you could simply loop through your arSelected array and set them to selected again.

All the best,
Anthony
price oem soft Wordpress Wordpress CMS

Adding Desktop Context Menu Entries in Vista

I like to think of myself as something of a power user when it comes to Microsoft Operating Systems in general. I should be, after 25 years of messing around with every new version except Millenium. I don't think they'll ever live that one down out in Redmond, and I personally don't think they should be allowed to live it down, ever. Ugh.

But I like to tweak. It's in my nature. I had Vista for all of two hours when I disabled UAC, but that was a matter more of necessity than anything else. It wouldn't let me install Apache or muck around with my classpath, which was both buggy and irritating. Of course, once UAC was dead, Apache installed just fine, and the world was a happy place in Anthony-land.

A little background on this tip: I spend a lot of time on remote servers. I get used to the way things are typically set up and organized, and I want windows to behave itself appropriate to the environment that pays my bills. When you Putty into a server to change system level settings, recompile a PHP distro, whatever the case may be, you're not faced with the same command line syntax or directory structure ("folder structure", if you wanna be like that) that you see in Windows. In Windows, you see something like:

c:\Program Files\Apache Group\....

and in *nix, it's more like

/usr/sbin/.....

So when I want to get into the conf/ directory for a website on the server, the commands look like this:

cd /var/www/vhosts/domain_name/conf
vim httpd.conf

And by default, Apache on Windows installed the htdocs folder and configured me up to:

c:\program files\Apache Foundation\Apache....\htdocs

Which made me keep doing mental gymnastics and wondering where I was, since I run just about everything on the command line. I came up with a solution that is likely to irritate the sensibilities of some people, since it means editing the dreaded registry... da da dummmmmm

(This tutorial assumes you have admin privileges. If you like, you can turn UAC back on later.)

Seriously, before you do anything in this tutorial, do this:

CODE:
  1. hold down the windows key
  2. press "r"
  3. type "regedit"
  4. Click on "Computer" waaaay up top
  5. Click File->Export and follow the command prompts

NOT backing up your registry is just plain irresponsible.

Ok, so now, for my purposes, I wanted to add a new command line window in a certain folder to the context menu for the desktop. First thing is to open regedit, just like we did, or if you're still in there after the export I know you did because you're a smart and thoughtful person, so much the better. Everyone else, open up regedit.

The stuff we're going to mess around with is located in:

CODE:
  1. [HKEY_CLASSES_ROOT\Directory\Background\shell]

Right-click on shell and select New->Key
Name this key something small and simple, don't ad any spaces. I find relevance helps.
In the values side of the window, you see something similar to:

CODE:
  1. Name          Type          Data
  2. Default        REG_SZ      (value not set)

Double-click on default, and enter a name for the context menu item ("Server Root", in my case).
Click Ok

Ok, so it should look something like this about now:

CODE:
  1. Directory
  2.     Background
  3.       shell
  4.         cmd
  5.         your_key_name

Right click on your key name (If you entered "paint", then click "paint"), and click New->Key again.
This time, you have to name the key [i]command[/i]
In the values pane on the right hand side, enter the command you want to execute when you click the entry.

So if I want to open a command line with a green background and yellow text open in a new mysql session, I would enter:

cmd.exe /T:2e /K mysql -u root -pmypassword

Or any other valid windows command.

~A!

PHP Expert Editor (Ankord Development Group)

Here at MPP, we're very big on supporting software companies who make great products that are reliable, trustworthy, and relatively free of bugs. When soemthing comes along that really makes us wince, though, we have to say something about it.

Such is the case with PHP Expert Editor, the PHP IDE from Ankord Development Group. It has very few features that the freeware Dev-PHP doesn't have, and it has a few things that the others don't.

  • Frequent Random Crashes - At least once a day, the application will simply stop working in the middle of typing a line of code. Repeated inquiries to support netted us zero replies.
  • Wonky laptop behavior - Our developers often use two or more monitors on their machines, and we're all on laptops. If we need to present to a group, we'll hook up to a projector. With PHP Expert Editor, disconnected or reconnecting an external monitor disables the ability to open a file or create new files until the application is restarted. This is exceedingly annoying.
  • Macros that simply don't work - There is a macro interface, but it's just an interface. Macros just don't work, no matter what you do.

Did I mention that it crashes randomly in the middle of writing code? Nothing like losing your work in all unsaved open files randomly and at the drop of a hat for seemingly no reason, definitely.
Normally, we don't complain about software too hard that we use from day to day. Then again, normally the software works.

Take it from a professional programming house, Ankord's PHP Expert Editor offering is a lemon, and their support has been abysmal in our experience. Forget purchasing it, get Dev-PHP instead. It has all the same features and doesn't lock up and die for no reason.

~A!

A Quick Note About header()

I've seen a great many questions come in lately on the use of the header() function in PHP. This is just a quick note to describe it's use and some of the issues surrounding it.

There are two basic types of headers when we talk about HTTP Header directives. Request Headers and Response Headers. Request headers are what your browser sends to a server, and response headers are what the server sends back. I've seen more complicated explanations, and they are accurate, but that's the essence of the thing.

When you specify a header with the header() function in PHP, you're sending a response header from the server 99.9% of the time. Most of the time, you're trying to use a header to:

  • Relocate to a different page
  • Download a file

Headers can be used for a number of different things, including setting cookies, but we're not going to look at that in this article. The cookie functions in PHP can handle everything you want to do with cookies.

Relocation:

When you're relocating to a different page from PHP, the function you use looks like this:

PHP:
  1. header("Location: http://somesite.com/page.php");

Which will send that header to the browser, causing it to head over to page.php on the somesite.com domain. So, you enter it into your code, and everything works, right?

Well, not always. See, when you don't specify any headers but send output to the browser (with print(), echo(), or just standard HTML), PHP is smart enough to send it's own. (PERL, not so much, but that's a different story). So when you've output anything, including whitespace to the browser, you get message telling you Headers have already been sent.
If you're not sure why, and you haven't output anything to the browser on purpose before the headers you're sending, the first thing to do is check for whitespace right before your opening PHP tag in your code. Resolve that there is none first.

If you want a little cleaner solution, you can use ob_start() and ob_flush() to send everything into an output buffer before it gets to the browser, and have it sent all at once.
One caveat here is that you want to call ob_flush() as soon as possible, because on scripts with large output, you can slow things down considerably.

Example without output buffers:

PHP:
  1. <?php
  2.   if ($redirect):
  3.     header("Location: http://somesite.com/redirect.php");
  4.     exit();
  5.   endif;
  6. ?>

exit() in the above example stops the script so nothing else will be executed. Without it, you can have the unintended consequence of doing something after you meant to redirect the user to a different page.

Example with output buffering:

PHP:
  1. <?php
  2.   ob_start();
  3.   if ($redirect):
  4.     header("Location: http://somesite.com/redirect.php");
  5.     exit();
  6.   endif;
  7. ?>
  8. <html>
  9. <body>
  10. Welcome to the site!</body>
  11. </body>
  12. </html>
  13. <?php
  14. ?>

~A!

Upgrading PHP from 4.3.9 to 5.2 on Cent OS4

I recently had to migrate a client from PHP 4.3.9 to 5.2 on a godaddy virtual dedicated server running Cent OS4, and I came across a fantastic guide for doing so:

http://www.jasonlitka.com/2006/11/30/upgrading-php-520-rhel-centos/

Unfortunately, I ran into a couple of problems with that guide, including broken links to a couple of RPMS and source packages that I corrected with forum searches and from the author's other posts, which are all fantastic. That is a great site, and Jason should be commended for his commitment to helping people do what they need to on Linux Servers.

I have assembled here the steps I took to upgrade, aggregating the information I got from Jason's site as well as the filling in I had to do.
So, without further ado, here are the steps I took:

1) Log into the server as root

2) mkdir /usr/src/redhat

3) chmod 777 -R /usr/src/redhat

4) yum install wget nano make autoconf automake rpm-build postfix fileutils file libtool gcc cpp gcc-c++ perl-DBI readline-devel libc-client-devel libstdc++-devel bzip2-devel curl-devel db4-devel expat-devel gmp-devel aspell-devel httpd-devel libjpeg-devel libpng-devel pam-devel openssl-devel sqlite-devel zlib-devel pcre-devel krb5-devel cyrus-sasl-devel openldap-devel postgresql-devel unixODBC-devel libxml2-devel net-snmp-devel libxslt-devel libxml2-devel expat-devel ncurses-devel gd-devel freetype-devel

5) wget http://www.jasonlitka.com/media/files/SRPMS/php-5.2.3-jason.2.src.rpm

6) rpm -ivh php-5.2.0-8.src.rpm

7) rpm -ivh php-pear-1.4.9-4.src.rpm

8) wget http://mirrors.kernel.org/fedora/core/6/source/SRPMS/pcre-6.6-1.1.src.rpm

9) rpm -ivh pcre-6.6-1.1.src.rpm

10) cd /usr/src/redhat/SPEC

11) rpmbuild pcre.spec

12)  cd /usr/src/redhat/RPMS/i386

13) rpm -Uvh pcre*

14) cd /usr/src/redhat/SPECS

15) pmbuild -bb php.spec

16) cd /usr/src/redhat/RPMS

17) rpm -Uvh php*rpm

At this point, php installed for me fine and dandy. Next, I updated the php.ini file to reflect the new modules directory, which was /usr/lib/php4 to the 5 version, which is /usr/lib/php/modules

Then I restarted apache to reflect the changes

18) /usr/sbin/apachectl -k graceful

After that, I just checked to make sure it had installed appropriately, and that mysql was working

19) php -v (Should display 5.2.3 for the version of PHP)

You can create a php file to check for the existence of mysql_connect() as I did, or you can create a file that actually connects to your database. Either one proves out the ability to connect to MySQL from your PHP installation.

Great big hat-tip to Jason Litka of http://jasonlitka.com for his doing the heavy lifting on most of this. The only things I had a problem with when following his guide were the PCRE version (it kept asking for >= 6.6) and a broken link to the php 5.2.2 source rpm on mirrors.kernel.org, which he fixed in this post on upgrading to 5.2.3 by providing his own source package.

Hope this helps anyone stuck with an outdated PHP version who wants to use actual object-oriented code and json functions from PHP.

~A!

Welcome University of Wisonsin Students!

Just a quick note to say hello to any students coming over from the University of Wisconsin - Eau Claire Database Management Courses.

We're happy to be able to help out in any way with your studies. If you have any questions about anything you see here, or need some help with programming or database tips and advice, please feel free to contact us at info@mypetprogrammer.com, and we'll be glad to give you a hand.

Good luck, and all the best,
~A!

Inline Values: The Ternary Operator

So, you have a text field, and you're using an associative array to fill the values based on table data from your RDBMS, right?

You're filling the values inline, something like:

value="<?=$row['name']?>"

Which is great, so long as you're sure the row will exist. If the row doesn't, you get an E_NOTICE telling you there's an undefined index. You could turn off error reporting, and poof, it works, or you could do it right.

Turning off error reporting to mask sloppy coding practices is like stopping doctor visits once you've been diagnosed with cancer. You're still sick, you're just not hearing about it any more. And just like a disease will continue to have adverse affects whether you admit it or not, your server's error log will fill up with undefined index and undeclared variable warnings and notices. Will this cause a long term server problem? Maybe, but I doubt it.

More important, filling up the server log with garbage makes you less able to diagnose real problems and fix them, because you have to sift through millions of lines of stupid notices and warnings to get to find a "real" error.

Let's say you're pulling the row like this, and assigning the array:

$result = mysql_query("select * from users where id=1");
$user = mysql_fetch_assoc($result);

If there is no record, you have a problem. Granted, most programmers I've seen are too sloppy and lazy to care about such a problem, but the problem still exists regardless of how you feel about it.

In a situation like the above (which is not the best way to access a DB, IMHO, use classes and good architecture), you can short circuit the issue by declaring the empty array first and then using a decision block to init the data if there is something to init.

$row = array();
$result = mysql_query("select * from users where id = 1");
if (mysql_num_rows($result)):
  $row = mysql_fetch_assoc($result);
endif;

This step alone does not solve your problem, it lays the foundation by which your problem can be solved. Now, when you do an inline value (interpolated into the HTML), do it with the ternary operator:

value="<?=$row ? $row['name'] : ""?>"

The ternary operator is a standard construct in most programming languages (VB6 had IIF, but it's the same thing). The Syntax of the ternary operator is:

condition ? truepart : falsepart

Where condition is any valid statement that translates into a boolean, truepart is what to do when it's true, and falsepart is what to do when it's false.

Let's take something a teensy bit more complicated. If you have a date in the database (let's say a DateTime type), and you want to initialize to the current date if the date in the table is empty, otherwise print the date as m/d/Y, the ternary operators can be nested like so:

value="<?=$row ? $row['date'] ? date('m/d/Y', strtotime($row['date'])) : date('m/d/Y') : date('m/d/Y')?>"

Confusing? Not so much. If we use some parentheses to section it off, it looks like:

value="<?="$row ? ($row['date'] ? date('m/d/Y', strtotime($row['date'])) : date('m/d/Y') ) : date('m/d/Y')?>"

Which is the same thing as doing this (in blocks):

if ($row):
   if ($row['date']):
     print date('m/d/Y', strtotime($row['date']));
   else:
     print date('m/d/Y');
   endif;
else:
   print date('m/d/Y');
endif;

Interpolation of PHP into HTML gets a bad rap either way, because it makes code harder to maintain, and a little ugly. But if you're going to do it, and many of us still do (I don't want to have the overhead and code size of something like Smarty all the time), then do it well and correctly.

And correctly includes the use ofthe htmlspecialchars() function, but that's a topic for another day.

~A!

WordPress Themes