Webmaster Resources
 

How to find duplicate values in a table column?

Filed under :SQL

There was an error with one of our application, and I needed to find table rows with duplicate values. The table column was not defined to have a unique index, but we weren’t anticipating duplicate values. I needed an easier way to identify duplicate values in a table with simple SQL statement.

Consider the following “employee” table:

id Name Alias Age
1 John Doe John 30
2 John Smith John 40
3 Joe Schmo Joe 38
4 Charlie Bohne Charlie 55

Assuming that we have an “employee” table with above values, and looking to find records with duplicate “Alias”. How do we retrieve them? With the following SQL statement with HAVING clause, we can easily accomplish that.


SELECT alias, count(alias) as count
FROM employee
GROUP BY alias
HAVING (count(alias) > 1)
ORDER BY alias

The above SQL statement will retrieve:

Alias Count
John 2

*NOTE: The HAVING clause allows SQL to use with aggregate functions with a condition whereas WHERE clause does not offer that functionality. For example, the HAVING clause can be used to retrieve SUM(x) > 100 or COUNT(y) > 1.

Did you like this? Share it:

How to install php-imagick on CentOS 5

Filed under :Linux

ImageMagick is a software suite to create, edit, compose or convert bitmap images. To use this utility in PHP, you’ll need to install ImageMagick Linux package and also build and install a PHP extension.

Prerequisite for installing imagick PHP extension is php-pear and gcc packages, so let’s get those packages installed.

# yum install php-pear gcc

Now, that you have php-pear and gcc, you may install ImageMagick packages.

# yum install ImageMagick ImageMagick-devel
# pecl install imagick

Note: You’ll not be able to run pecl if you don’t have php-pear package installed. To compile imagick, you’ll need a GCC compiler as well.

By running the command, you’ll install ImageMagick and PHP extension module imagick.so in the /usr/lib/php/modules folder. If you have a 64-bit machine, the modules directory will be /usr/lib64/php/modules.

Edit the /etc/php.d/imagick.ini, and add the following line.

extension=imagick.so

Restart apache, by …

# service httpd restart

That’s all there is to it.

Did you like this? Share it:

Multiple Constructors in PHP

Filed under :PHP

In most object-oriented programming languages such as Java, C++ and C#, you can define multiple constructors each having different signatures. The class calls correct constructor based on the number of parameters, and data type of input parameters. In PHP5, however, you can have one and only one constructor. Constructor in PHP is defined with a reserved keyword, __construct(). If the __construct function doesn’t exist, PHP5 will search for the old-style constructor function by the name of the class.

Not being able to define multiple constructors in PHP5 is a big limitation. How do we work around this limitation, and create objects with varying initial values? There are a couple of ways to workaround the problem, and here are the solutions.

1. Use func_get_args() and func_num_args()

class Example {
    function __construct() {
        $argv = func_get_args();
        switch( func_num_args() ) {
            case 1:
                self::__construct1($argv[0]);
                break;
            case 2:
                self::__construct2( $argv[0], $argv[1] );
                break;
            case 3:
                self::__construct2( $argv[0], $argv[1], $argv[2] );
         }
    }
 
    function __construct1($arg1) {
    ...
    }
 
    function __construct2($arg1, $arg2) {
    ...
    }
 
    function __construct3($arg1, $arg2, $arg3) {
    ...
    }
}
 
$a = new Example("Argument 1");
$b = new Example("Argument 1", "Argument 2");
$b = new Example("Argument 1", "Argument 2", "Argument 3");

2. Use “static” Factory Pattern.

The factory pattern allows for the instantiation of objects at runtime, which may be used to mimic creation of each object with different factory methods. Instead of creating multiple constructors, you can define one factory method for each constructor.

class Example {
 
    public static function factory1($arg1) {
    }
 
    public static function factory2($arg1, $arg2) {
    }
}
 
$a = new Example::factory1("Argument 1");
$b = new Example::factory2("Argument 1", "Argument 2");
Did you like this? Share it:

Copy and Paste Word document to HTML form

Filed under :HTML

Many users without computer knowledge copy contents from a word document, and paste them into a HTML form (<textarea></textarea>) and expect to retain formating as well as special characters such as smart quotes and emdashes. You may opt to translate smart quotes to regular quotes and emdashes to regular dashes with a PHP script. If any user submits a non-ASCII character contents, you’ll probably see weird characters in the database and HTML page. Finding and fixing just a few of them (curly quotes and em dashes) isn’t going to solve the real problem.

How do you go about resolving this problem? One way to solve the problem is by educating the users to convert the special characters into ASCII text and submit them into the form. To convert special characters, you may use any of the following methods.

1. Save the word document as a HTML document. Microsoft Word has an option to save .DOC document into a .HTML file. Select the contents from the HTML document, and paste them into the HTML form.

2. Copy the Word contents, and paste them into a notepad; then select the same contents from the notepad, copy and paste them into the HTML form.

Did you like this? Share it:

How to enable or suppress PHP errors?

Filed under :PHP

PHP gives a programmer an ability to control logging of errors, and the types of errors to be logged. This can be done in one of two ways: (1) Runtime Configuration, and (2) at the script level.

The runtime configuration is stored in the php.ini, and it sets the default for all php scripts.

; error_reporting is a bit-field. Or each number up to get desired error
; reporting level
; E_ALL – All errors and warnings (doesn’t include E_STRICT)
; E_ERROR – fatal run-time errors
; E_WARNING – run-time warnings (non-fatal errors)
; E_PARSE – compile-time parse errors
; E_NOTICE – run-time notices (these are warnings which often result
; from a bug in your code, but it’s possible that it was
; intentional (e.g., using an uninitialized variable and
; relying on the fact it’s automatically initialized to an
; empty string)
; E_STRICT – run-time notices, enable to have PHP suggest changes
; to your code which will ensure the best interoperability
; and forward compatibility of your code
; E_CORE_ERROR – fatal errors that occur during PHP’s initial startup
; E_CORE_WARNING – warnings (non-fatal errors) that occur during PHP’s
; initial startup
; E_COMPILE_ERROR – fatal compile-time errors
; E_COMPILE_WARNING – compile-time warnings (non-fatal errors)
; E_USER_ERROR – user-generated error message
; E_USER_WARNING – user-generated warning message
; E_USER_NOTICE – user-generated notice message
;
; Examples:
;
; – Show all errors, except for notices and coding standards warnings
;

error_reporting = E_ALL & ~E_NOTICE

; Print out errors (as a part of the output). For production web sites,
; you’re strongly encouraged to turn this feature off, and use error logging
; instead (see below). Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.

display_errors = Off

To override default error configuration set forth by the php.ini, a programmer may selectively add the following php settings to enable or suppress PHP errors. This is useful in debugging PHP errors, and Internal Server Errors (500).

ini_set(“display_errors”, 1);
error_reporting(E_ALL);

You may also use error control operator, @, to control error at the line level instead of script level.

if (@$x == 1) {
    echo “true”;
}

If $x is undefined, an E_NOTICE error will be displayed if display_errors is turned on and error_reporting is set at the E_NOTICE level. By adding ‘@’ control operator to a statement, the error message is suppressed.

Did you like this? Share it:

PHP $_SERVER environment variable

Filed under :Linux

PHP provides a large number of predefined variables to all scripts, and $_SERVER array is commonly used to refer server-specific environment information. Per PHP.net documentation, the $_SERVER variable is defined as:

Description
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those.

$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)

Indices

$_SERVER['PHP_SELF']: The filename of the currently executing script, relative to the document root. No query string will be returned. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php?abc=123 would be /test.php. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.

http://example.com/server.php?a=1&b=2&c=3  ==>  /server.php

$_SERVER['GATEWAY_INTERFACE']: What revision of the CGI specification the server is using; i.e. ‘CGI/1.1′.

http://example.com/server.php?a=1&b=2&c=3  ==>  CGI/1.1

$_SERVER['SERVER_ADDR']: The IP address of the server under which the current script is executing.

http://example.com/server.php?a=1&b=2&c=3  ==>  69.67.216.167

$_SERVER['SERVER_NAME']: The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

http://example.com/server.php?a=1&b=2&c=3  ==>  example.com

$_SERVER['SERVER_SOFTWARE']: Server identification string, given in the headers when responding to requests.

http://example.com/server.php?a=1&b=2&c=3  ==>  Apache/2.2.3 (CentOS)

$_SERVER['SERVER_PROTOCOL']: Name and revision of the information protocol via which the page was requested; i.e. ‘HTTP/1.0′;

http://example.com/server.php?a=1&b=2&c=3  ==>  HTTP/1.1

$_SERVER['SERVER_METHOD']: Which request method was used to access the page; i.e. ‘GET’, ‘HEAD’, ‘POST’, ‘PUT’. (Note: PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.)

http://example.com/server.php?a=1&b=2&c=3  ==>  

$_SERVER['REQUEST_TIME']: The timestamp of the start of the request. Available since PHP 5.1.0.

http://example.com/server.php?a=1&b=2&c=3  ==>  1307744457

$_SERVER['QUERY_STRING']: The query string, if any, via which the page was accessed.

http://example.com/server.php?a=1&b=2&c=3  ==>  a=1&b=2&c=3

$_SERVER['DOCUMENT_ROOT']: The document root directory under which the current script is executing, as defined in the server’s configuration file.

http://example.com/server.php?a=1&b=2&c=3  ==>  /var/www/html

$_SERVER['HTTP_ACCEPT']: Contents of the Accept: header from the current request, if there is one.

http://example.com/server.php?a=1&b=2&c=3  ==>  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

$_SERVER['HTTP_ACCEPT_CHARSET']: Contents of the Accept-Charset: header from the current request, if there is one. Example: ‘iso-8859-1,*,utf-8′.

http://example.com/server.php?a=1&b=2&c=3  ==>  ISO-8859-1,utf-8;q=0.7,*;q=0.3

$_SERVER['HTTP_ACCEPT_ENCODING']: Contents of the Accept-Encoding: header from the current request, if there is one. Example: ‘gzip’.

http://example.com/server.php?a=1&b=2&c=3  ==>  gzip,deflate,sdch

$_SERVER['HTTP_ACCEPT_LANGUAGE']: Contents of the Accept-Language: header from the current request, if there is one. Example: ‘en’.

http://example.com/server.php?a=1&b=2&c=3  ==>  en-US,en;q=0.8

$_SERVER['HTTP_CONNECTION']: Contents of the Connection: header from the current request, if there is one. Example: ‘Keep-Alive’.

http://example.com/server.php?a=1&b=2&c=3  ==>  keep-alive

$_SERVER['HTTP_HOST']: Contents of the Host: header from the current request, if there is one.

http://example.com/server.php?a=1&b=2&c=3  ==>  example.com

$_SERVER['HTTP_REFERER']: The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

http://example.com/server.php?a=1&b=2&c=3  ==>  

$_SERVER['HTTP_USER_AGENT']: Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page’s output to the capabilities of the user agent.

http://example.com/server.php?a=1&b=2&c=3  ==>  Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.91 Safari/534.30

$_SERVER['HTTPS']: Set to a non-empty value if the script was queried through the HTTPS protocol. (Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.)

http://example.com/server.php?a=1&b=2&c=3  ==>  

https://example.com/server.php?a=1&b=2&c=3  ==>  On

$_SERVER['REMOTE_ADDR']: The IP address from which the user is viewing the current page.

http://example.com/server.php?a=1&b=2&c=3  ==>  24.15.238.72

$_SERVER['REMOTE_HOST']: The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user. (Note: Your web server must be configured to create this variable. For example in Apache you’ll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().)

http://example.com/server.php?a=1&b=2&c=3  ==>  49857

$_SERVER['REMOTE_PORT']: The port being used on the user’s machine to communicate with the web server.

http://example.com/server.php?a=1&b=2&c=3  ==>  

$_SERVER['SCRIPT_FILENAME']: The absolute pathname of the currently executing script. (Note: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.)

http://example.com/server.php?a=1&b=2&c=3  ==>  /var/www/html/server.php

$_SERVER['SERVER_ADMIN']: The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.

http://example.com/server.php?a=1&b=2&c=3  ==>  admin@topwebhosts.org

$_SERVER['SERVER_PORT']: The port on the server machine being used by the web server for communication. For default setups, this will be ’80′; using SSL, for instance, will change this to whatever your defined secure HTTP port is.

http://example.com/server.php?a=1&b=2&c=3  ==>  80

$_SERVER['SERVER_SIGNATURE']: String containing the server version and virtual host name which are added to server-generated pages, if enabled.

http://example.com/server.php?a=1&b=2&c=3  ==>  Apache/2.2.3 (CentOS) Server at www.topwebhosts.org Port 80

$_SERVER['PATH_TRANSLATED']: Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping. (Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it’s set to the same value as the SCRIPT_FILENAME server variable when it’s not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.)

http://example.com/server.php?a=1&b=2&c=3  ==>  

$_SERVER['SCRIPT_NAME']: Contains the current script’s path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.

http://example.com/server.php?a=1&b=2&c=3  ==>  /server.php

$_SERVER['REQUEST_URI']: The URI which was given in order to access this page; for instance, ‘/index.html’.

http://example.com/server.php?a=1&b=2&c=3  ==>  /server.php?a=1&b=2&c=3

$_SERVER['PHP_AUTH_DIGEST']: When doing Digest HTTP authentication this variable is set to the ‘Authorization’ header sent by the client (which you should then use to make the appropriate validation).

http://example.com/server.php?a=1&b=2&c=3  ==>  

$_SERVER['PHP_AUTH_USER']: When doing HTTP authentication this variable is set to the username provided by the user.

http://example.com/server.php?a=1&b=2&c=3  ==>  

$_SERVER['PHP_AUTH_PW']: When doing HTTP authentication this variable is set to the password provided by the user.

http://example.com/server.php?a=1&b=2&c=3  ==>  

$_SERVER['AUTH_TYPE']: When doing HTTP authenticated this variable is set to the authentication type.

http://example.com/server.php?a=1&b=2&c=3  ==>  

$_SERVER['PATH_INFO']: Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff.

http://example.com/server.php?a=1&b=2&c=3  ==>  

$_SERVER['ORIG_PATH_INFO']: Original version of ‘PATH_INFO’ before processed by PHP.

http://example.com/server.php?a=1&b=2&c=3  ==>  

To learn the differences between the PHP_SELF, SCRIPT_NAME and REQUEST_URI, please consult http://php.about.com/od/learnphp/qt/_SERVER_PHP.htm.

Did you like this? Share it:

How to reverse a MySQL result set?

Filed under :PHP, SQL

I need to grab last 100 rows of a MySQL table, and loop them through in reverse order. The array_reverse() PHP function won’t reverse the “resource” or “array” data types, so it isn’t as easy to reverse the array of “mixed” data type. The best way to achieve this is by using a SQL statement as shown below.

SELECT * FROM (SELECT * FROM mytable ORDER BY id DESC limit 100) AS foo ORDER BY id ASC;

You may also retrieve the MySQL result set in descending order, and traverse the set in reverse order.

/* fetch MySQL result set in reverse order */
for ($i = mysql_num_rows($resultset) – 1; $i >= 0; $i–) {
    mysql_data_seek($resultset, $i);
    $row = mysql_fetch_assoc($result);
    echo $row['abc'] . ‘ ‘ . $row['xyz'] . “\n”;
}

Did you like this? Share it:

How to install Subversion on SuSE Linux?

Filed under :Linux

I’ve had a chance to install Subversion on Windows machines in the past, but this is my first try on SuSE Linux. The process is pretty straight forward, and it’s fairly easy to follow. Here is the run down summary of how to get started.

1. Use Zypper to install the following modules:

# zypper install subversion subversion-tools apache2

2. Once you have required software modules, installed browse the following README file to setup your subversion repositories.

less /usr/share/doc/packages/subversion/README.SuSE

That’s all! Shouldn’t take anymore than an hour to complete the job.

Did you like this? Share it:

Double and Triple equal operators in PHP

Filed under :PHP

Even if you’re a seasoned programmer, you may not have seen triple equals operator in most programming languages. In PHP, the triple equals (===) operator was introduced in version 4 and it checks for equality similar to double equals (==) operator but also checks type of variable. Here are the differences between single, double and triple equals operators.

A single equals operator (=) is an assignment operator – take what’s on the right as an expression and save it in the variable named on the left.

$a = 5; // A is assigned an integer value 5.

A double equals operator (==) is a comparison operator and it tests the value (variable, expression or constant) of left to the right for equality. If the values are the same, it returns true.

$a = 5;
$b = “5″;
if ($a == $b) echo “same”; // Returns TRUE

A triple equals operator (===) is a comparison operator and it tests the value (variable, expression or constant) of left to the right for identicalness. The value of left and right have to be equal AND the type has to be equal as well. (i.e. both are strings or both are integers).

$a = 5;
$b = “5″;
if ($a === $b) echo “same”; // Returns FALSE

For more information about equals operators, please visit PHP Manual.

Did you like this? Share it:

Assigning name/value pair from a single element array to variables

Filed under :Linux

How do you extract name/value pair of an associative array into PHP variables? Whether it’s a single element array, or multiple element array the procedure is identical.

$coins = array(“penny” => 1, “nickle” => 5, “dime” => 10, “quarter” => 25);
foreach ($coins as $name => $value) {
echo “$name -> $value\n”;
}

while(list($name, $value) = each($coins)) {
echo “$name -> $value\n”;
}

If you have a multi-dimentional array with a single element in an array for multi-element relationship (name/name/value, or name/value/value), you may use the following:

$family = array(
“dad” => array(“scott” => 45),
“mom” => array(“karen” => 43),
“son1″ => array(“ryan” => 16),
“daughter” => array(“cindy” => 18),
“son2″ => array(“andrew” => 13));

foreach($family["dad"] as $name => $age);
echo “(Dad) name: $name, age: $age\n”;

list($name, $age) = each($family["mom"])
echo “(Mom) name: $name, age: $age\n”;

Basically, the foreach and list/each commands achieve the same goal.

Did you like this? Share it:


WEB HOSTING RESOURCES