Disable Javascript Errors

This simple script will prevent javascript errors from being displayed in your visitor's browser

<script type="text/javascript">
function noError(){return true;}
window.onerror = noError;
</script>

Or jQuery:


$(window).error(function(){
return true;
});

The functionality is very simple: create a function that always returns true, and then whenever an error occurs, call this function (returning true and suppressing the error).


Shamefully, this script is only tested in IE.

Labels: ,

URLLoader Error #2032: Stream Error

This error can be caused by requesting a URL that is over the maximum length supported by Internet Explorer, which is 2083. This can be confusing, because if you copy a URL you are trying to load in Flex with a URLRequest into Internet Explorer, IE will truncate the URL itself, and appear to load properly.

This is especially important for REST API's that can take a long string variable.

The following code will avoid this issue.

var URL_MAX_LENGTH:int = 2083;
var request:URLRequest = new URLRequest(url.substr(0, URL_MAX_LENGTH));

[www.brighthub.com]

Labels:

Detect Window Resize

When I try that - it works fine for me and I get the alert.  I am also using IE6 on WinXP.  My body tag looks like this:

<body onResize="alert('body resize');">

There is another way to do the same thing, and perhaps that method may work for you when this one doesn't for some reason.  Put a script tag in your page like this:


<script language="Javascript">
document.body.onresize = function (){
alert("Thanks for resizing!");
}
</script>

That method also works for me, and it may work for you too.

Labels:

Database Class using PHP

Hi PHP Developers,
I wrote a Database utility class, which is used mostly in any projects. If you've this class, then you don't need to write queries each & every time when a new project comes. You can just copy this file & paste it in your class directory & can call it anytime. The class written below is very simple & it can be understood to the novice also. There will be a way to minimize the functions & statements inside the class too, if so, don't regret to post it in comments.

 

<?php
/*-----------------------------------------------------------------------
Created By: Sathish Kumar.R
Date: 30 July 2010
E-mail: smart2raise[at]gmail[dot]com
Purpose: Database Manipulation


Functions Available:
db: Constructor (for mysql connect)
query: Executing query(mysql_query)
num_rows: Finding total rows(mysql_num_rows)
fetch_object: Fetch results in Object (mysql_fetch_object)
fetch_array: Fetch results in Array (mysql_fetch_array)
fetch_assoc: Fetch results in Array (mysql_fetch_assoc)
insert: Insert query (Insert into...)
insert_id: Gets last inserted ID (mysql_insert_id)
update Update query (Update ...)
delete Delete query (Delete ...)
countof: Count function in mysql
maxof: Max function in mysql
sumof: Sum function in mysql
avgof: AVG function in mysql
last_query: Displays the query which you executed last
throw_error: If any mysql error occurs & you set $debug = true then it will show the query & the mysql error
-------------------------------------------------------------------------*/
class db{
var $debug = false;
var $query = array();
var $prefix = "";
function db($server,$username,$pwd,$db){
mysql_connect($server,$username,$pwd) or die('Please check your database connection');
mysql_select_db($db);
}
function query($qry){
$this->query[] = $qry;
$res = mysql_query($qry);
if(mysql_error()){
$this->throw_error();
}
return $res;
}
function num_rows($res){
return mysql_num_rows($res);
}
function fetch_object($res){
$fet = mysql_fetch_object($res);
return $fet;
}
function fetch_array($res){
$fet = mysql_fetch_array($res);
return $fet;
}
function fetch_assoc($res){
$fet = mysql_fetch_assoc($res);
return $fet;
}
function insert($val,$table){
$query = 'INSERT INTO '.$table.' (';
foreach ($val AS $key => $value)
$query .= '`'.$key.'`,';
$query = rtrim($query, ',').') VALUES (';
foreach ($val AS $key => $value){
if(get_magic_quotes_gpc())
$query .= '\''.$value.'\',';
else
$query .= '\''.mysql_real_escape_string($value).'\',';
}
$query = rtrim($query, ',').')';
return $this->query($query);
}
function insert_id(){
return mysql_insert_id();
}
function update($val,$table,$con){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else
{
$where = "";
}
$query = 'update '.$table.' set ';
foreach ($val AS $key => $value){
if(get_magic_quotes_gpc())
$query .= $key."=".'\''.$value.'\',';
else
$query .= '\''.mysql_real_escape_string($value).'\',';
}
$query = rtrim($query, ',')." ".$where;
return $this->query($query);
}
function delete($table,$con){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else {
$where = "";
}
return $this->query("delete from {$table} {$where}");
}
function countof($col,$table,$con="",$group=""){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else {
$where = "";
}
if($group!="")
$groupby = "group by ".$group;
else
$groupby = "";
$query = $this->query("select count({$col}) from {$table} {$where} {$groupby}");
$fet = $this->fetch_array($query);
return $fet[0];
}
function maxof($col,$table,$con="",$group=""){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else {
$where = "";
}
if($group!="")
$groupby = "group by ".$group;
else
$groupby = "";
$query = $this->query("select max({$col}) from {$table} {$where} {$groupby}");
$fet = $this->fetch_array($query);
return $fet[0];
}
function sumof($col,$table,$con="",$group=""){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else {
$where = "";
}
if($group!="")
$groupby = "group by ".$group;
else
$groupby = "";
$query = $this->query("select sum({$col}) from {$table} {$where} {$groupby}");
$fet = $this->fetch_array($query);
return $fet[0];
}
function avgof($col,$table,$con="",$group=""){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else {
$where = "";
}
if($group!="")
$groupby = "group by ".$group;
else
$groupby = "";
$query = $this->query("select avg({$col}) from {$table} {$where} {$groupby}");
$fet = $this->fetch_array($query);
return $fet[0];
}
function last_query(){
return end($this->query);
}
function throw_error(){
if($this->debug==true){
$qry = "<span style="color: rgb(0, 0, 0);">".end($this->query)."</span>
";
}
else{
$qry = "";
}
die("<div style='width:500px; margin:auto; text-align:left; color:red; font-size:12px;border:2px solid #FFD700;vertical-align:middle; line-height:19px;background:#FFFFDD;font-family:verdana;padding:3px;'>".$qry."Mysql Error: ".mysql_error());
}
}
?>

<?php
//Usage of Class:


$hostname = "hostname";
$username = "username";
$password = "";
$database = "dbname";
$db = new db($hostname,$username,$password,$database);
$db->debug = true;
//If it is set to true, then mysql error will shown the query which throws the error.

$qry = $db->query("select columnname from tablename"); //Executing query
$db->num_rows($qry); //Finding total rows

$val = array("a"=>123,"b"=>"sathish","c"=>"kumar");

$a = $db->insert($val,"tablename");
/*Note: $val should be an array, else it will throw error Key in an array should be the column name in the table & value can be any value */

$db->insert_id(); //returns the last inserted ID in the database

$val1 = array("a"=>123,"b"=>"Sathish","c"=>"Kumar");

$db->update($val1,"tablename",array("id"=>2));
/*
Update query same as insert query, you can pass multiple conditions in the 3rd argument i.e array("id"=>2,"a"=>'123')
*/

$db->delete("tablename",array("id"=>4));
//You can pass multiple conditions in 2nd argument


$db->countof("id","tablename",array("a"=>123123));


$db->maxof("id","tablename",array("a"=>123123));


$db->avgof("id","tablename",array("a"=>123123));

/*
for countof(),maxof(),avgof() you can pass additional argument group by


$db->countof("id","tablename",array("a"=>123123),"c");

this will result as "select count(id) where a = '123123' group by c"
*/

$db->last_query() //This will return last executed query
?>
Labels: ,

Automatic database INSERT/UPDATE class

I built this class because i wanted to have a shortcut for all the times i need to insert or update rows into the database.
The main purpose of this class it to use it when you submit forms.

<?php
/**
* db.class.php
*/
class DB {
/**
* Inserts one item into a table
*
* @param string $table The name of the table
* @param array $items Array of fields to insert (if some is not specified the default value is assumed)
* @return int The new ID of the item
*/
public function insertTableRow($table, $items) {
$this->fixQuotes($items);
$fields = $this->getTableFieldsInfo($table);
$query = "INSERT INTO `$table` (";
foreach ($fields as $info)
$query .= '`'.$info->name.'`, ';
$query = trim($query, ', ');
$query .= ") VALUES(";
foreach ($fields as $info) {
if (isset($items[$info->name])) {
if (strtoupper($items[$info->name]) == "NULL")
$val = "NULL, ";
else
$val = "'".$items[$info->name]."', ";
}
else
$val = "'".$items[$info->def]."', "; //
$query .= $val;
}
$query = trim($query, ', ');
$query .= ")";
//print $query;
$r = mysql_query($query);
return mysql_insert_id();
}
/**
* Updates a table
*
* @param string $table The name of the table
* @param int $id The ID of the row to update
* @param array $items Array of new values ($items['columnName']['value'])
* @return TRUE on success or FALSE on error
*/
public function updateTableRow($table, $id, $items) {
$this->fixQuotes($items);
$fields = $this->getTableFieldsInfo($table);

$query = "UPDATE `$table` SET ";
foreach ($fields as $info) {
if (isset($items[$info->name])) {
if ($items[$info->name] == 'NULL')
$query .= "`".$info->name."` = NULL, ";
else
$query .= "`".$info->name."` = '".$items[$info->name]."', ";
}
}
$query = trim($query, ', ');
$query .= " WHERE ID='$id'";
$r = mysql_query($query);
//print $query;

return $r;
}
//----------------------------------- PROTECTED -----------------------------------//
/**
* Returns an object containing all the fields info of a table
*
* @param strin $table The name of the table
* @return object The fields info as an array of objects like:
* blob: $fieldInfo->blob
* max_length: $fieldInfo->max_length
* multiple_key: $fieldInfo->multiple_key
* name: $fieldInfo->name
* not_null: $fieldInfo->not_null
* numeric: $fieldInfo->numeric
* primary_key: $fieldInfo->primary_key
* table: $fieldInfo->table
* type: $fieldInfo->type
* default: $fieldInfo->def
* unique_key: $fieldInfo->unique_key
* unsigned: $fieldInfo->unsigned
* zerofill: $fieldInfo->zerofill
*/
protected function getTableFieldsInfo($table) {
$query = "SELECT * FROM `$table`";
$result = mysql_query($query);
while ($meta = mysql_fetch_field($result)) {
if ($meta)
$fieldInfo[] = $meta;
}
mysql_free_result($result);
return $fieldInfo;
}
/**
* Fixes single quotes in a string (or array of strings) to store it into the DB without error
* @param mixed $str The string or array of strings to fix (by reference)
*/
protected function fixQuotes(&$str) {
if (is_array($str)) {
foreach ($str as $key=>$text)
$str[$key] = str_replace("'", "''", $text);
}
else
$str = str_replace("'", "''", $str);
}
}
?>

Usage

Let’s see a very practical example to understand how this class can be very useful.


Assume we have a page with a form to submit contact information. First, we need a contact table with these fields:



  • ID

  • first_name

  • middle_name

  • last_name

  • biography


CREATE TABLE `contact` (
`ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`first_name` VARCHAR( 128 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`middle_name` VARCHAR( 128 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`last_name` VARCHAR( 128 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`biography` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL

) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;

Then, we need a file containing the form, for example form.php:


<?php
/**
* form.php
*/
include "db.class.php";
if (isset($_POST['submit'])) {
$DB = new DB();
$DB->insertTableRow('contact', $_POST);
}
else {
echo '
<form action="form.php" method="POST" target="_self">
<p>First Name<br />
<input type="text" name="first_name" value="" /></p>
<p>Middle Name<br />
<input type="text" name="middle_name" value="" /></p>
<p>Last Name<br />
<input type="text" name="last_name" value="" /></p>
<p>Biography<br />
<textarea name="biography"></textarea></p>
<p><input type="submit" value="Submit" /></p>
</form>
';
}
?>

Explanation

The method DB::insertTableRow accepts 2 arguments:



  1. the name of the table

  2. an array of values where the keys must match exactly the name of the columns of the table, and the value can be anything


The nice thing is that:



  1. you don’t have to fill the array with ALL the fields (if you don’t pass a field, the class will automatically detect the default value and store that instead)

  2. the order of the array values doesn’t have to match the order of the fields in the table

  3. the method DB::updateTableRow works the same way:


<?php

//Example 1:

/*
If we want to add another row, this time without a form (the form was only an example to show how easy it is to use the class with forms),
and we know only first name and last name of the person, we just call the method like this:
*/
$DB->insertTableRow ('contact', array ('first_name'=>'Robert', 'last_name'=>'De Niro'));

//---------------------//

//Example 2:
$contact['first_name'] = 'Robert';
$contact['last_name'] = 'De Niro';
$contact['address'] = 'Holliwood';

$DB->insertTableRow ('contact', $contact);

/*
NOTE:
our second example has a field 'address' that doesn't exist in our table!!
It doesn't matter, the class method will only care of those fields that have the same name of one of the columns, and ignore all the others!
*/

//-----------------------------------------------------------------//

//Example 3:
/*
If we want to update the contact table and change the first name of our contact we just need to
pass an array of 1 element where key is the name of the column we want to change and the value is the new name
*/
$DB->updateTableRow ('contact', array('first_name'=>'Peter');

?>
Labels: ,

Javascript to Redirect a Drop Down List (select)

You can redirect using an html select without having to place it in a form, or have the user press a button. The user only needs to change the value.

Check out the following code that you can copy and paste into an html file and take for a test drive:

<html>

<head>
<title>Drop Down List Redirect</title>
</head>

<body>

<select onchange="top.location.href = 'http://www.google.com/search?q='
+ this.options[ this.selectedIndex ].value" >
<option value="">None</option>
<option value="cute+dogs">Cute Dogs</option>
<option value="lasers+beams">Laser Beams</option>
<option value="kitty+cat">Kitty Cat</option>
</select>

</body>
</html>

Breaking down the javascript code into more understandable chunks gives:

// 'this' points to the select object after change the item in the drop down list.
var drop_down = this;

// drop_down.selectedIndex contains the position of the item that was selected from the drop down
var selected_index = drop_down.selectedIndex;

// drop_down.options contains all of html option elements inside the html select
// we need to go to .value to get the 'value="something"' written in the HTML
var selected_value = drop_down.options[ selected_index ].value;

// changing top.location.href redirects ( unless you only append #blah )
top.location.href = 'http://www.google.com/search?q=' + selected_value


I hope you guys find this helpful!



Cheers,

Joseph

Labels: ,

Modify HTTP Headers with PHP

// See related links for more status codes

// Use this header instruction to fix 404 headers
// produced by url rewriting...
header('HTTP/1.1 200 OK');

// Page was not found:
header('HTTP/1.1 404 Not Found');

// Access forbidden:
header('HTTP/1.1 403 Forbidden');

// The page moved permanently should be used for
// all redrictions, because search engines know
// what's going on and can easily update their urls.
header('HTTP/1.1 301 Moved Permanently');

// Server error
header('HTTP/1.1 500 Internal Server Error');

// Redirect to a new location:
header('Location: http://www.example.org/');

// Redriect with a delay:
header('Refresh: 10; url=http://www.example.org/');
print 'You will be redirected in 10 seconds';

// you can also use the HTML syntax:
// <meta http-equiv="refresh" content="10;http://www.example.org/ />

// override X-Powered-By value
header('X-Powered-By: PHP/4.4.0');
header('X-Powered-By: Brain/0.6b');

// content language (en = English)
header('Content-language: en');

// last modified (good for caching)
$time = time() - 60; // or filemtime($fn), etc
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');

// header for telling the browser that the content
// did not get changed
header('HTTP/1.1 304 Not Modified');

// set content length (good for caching):
header('Content-Length: 1234');

// Headers for an download:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile('example.zip');

// Disable caching of the current document:
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');

// set content type:
header('Content-Type: text/html; charset=iso-8859-1');
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain'); // plain text file
header('Content-Type: image/jpeg'); // JPG picture
header('Content-Type: application/zip'); // ZIP file
header('Content-Type: application/pdf'); // PDF file
header('Content-Type: audio/mpeg'); // Audio MPEG (MP3,...) file
header('Content-Type: application/x-shockwave-flash'); // Flash animation

// show sign in box
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
print 'Text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';
Labels:

Fixing mod_rewrite and .htaccess on GoDaddy Hosting

I recently launched a new website on GoDaddy shared hosting. The website required mod_rewrite for SEO-friendly URLs. GoDaddy provides mod_rewrite but every time I tried to hit a two-deep URL, I would get a 404 error. Here's what I had:

# Mod Rewrite
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

The fix to this problem was to add the following directive before my mod_rewrite directives:


#Fix Rewrite
Options –Multiviews

Tada! The URLs began working and the website's SEO has taken off!


[credit: davidwalsh.name]

Labels:
2010 WEBSITE20. All rights reserved.