PHP 5.3 Alpha Review

PHP has released 5.3 as a dereview

THIS IS A DEVELOPMENT PREVIEW - DO NOT USE IT IN PRODUCTION!

The purpose of this alpha release is to encourage users to not only actively participate in identifying bugs, but also in ensuring that all new features or necessary backwards compatibility breaks are noted in the documentation. Please report any findings to the QA mailinglist or the bug tracker.

There have been a great number of other additions and improvements since the last alpha, but here is a short overview of the most important changes:

* Namespaces (documentation has been updated to the current state)
* Rounding behavior
* ext/msql has been removed, while ext/ereg will now raise E_DEPRECATED notices
* ext/mhash has been replaced by ext/hash but full BC is maintained
* PHP now uses cc as the default compiler, instead of gcc
* A number of bug fixes to ext/pdo, ext/soap, the stream layer among others

Several under the hood changes also require in depth testing with existing applications to ensure that any backwards compatibility breaks are minimized.

Leave a Comment

MySQL Using Triggers

Support for triggers is included beginning with MySQL 5.0.2. A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. Some uses for triggers are to perform checks of values to be inserted into a table or to perform calculations on values involved in an update.

A trigger is defined to activate when an INSERT, DELETE, or UPDATE statement executes for the associated table. A trigger can be set to activate either before or after the triggering statement. For example, you can have a trigger activate before each row that is inserted into a table or after each row that is updated.

Syntax

To create a trigger or drop a trigger, use the CREATE TRIGGER or DROP TRIGGER statement.

Trigger with a table for INSERT statements

mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));

mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account
-> FOR EACH ROW SET @sum = @sum + NEW.amount;

The CREATE TRIGGER statement creates a trigger named ins_sum that is associated with the account table. It also includes clauses that specify the trigger activation time, the triggering event, and what to do with the trigger activates:

*      The keyword BEFORE indicates the trigger action time. In this case, the trigger should activate before each row inserted into the table. The other allowable keyword here is AFTER.

*      The keyword INSERT indicates the event that activates the trigger. In the example, INSERT statements cause trigger activation. You can also create triggers for DELETE and UPDATE statements.

*      The statement following FOR EACH ROW defines the statement to execute each time the trigger activates, which occurs once for each row affected by the triggering statement In the example, the triggered statement is a simple SET that accumulates the values inserted into the amount column. The statement refers to the column as NEW.amount which means “the value of the amount column to be inserted into the new row.”

To use the trigger, set the accumulator variable to zero, execute an INSERT statement, and then see what value the variable has afterward:

mysql> SET @sum = 0;
mysql> INSERT INTO account VALUES(137,14.98),(141,1937.50),(97,-100.00);
mysql> SELECT @sum AS ‘Total amount inserted’;
+———————–+
| Total amount inserted |
+———————–+
| 1852.48               |
+———————–+

In this case, the value of @sum after the INSERT statement has executed is 14.98 + 1937.50 - 100, or 1852.48.

To destroy the trigger, use a DROP TRIGGER statement. You must specify the schema name if the trigger is not in the default schema:

mysql> DROP TRIGGER test.ins_sum;

Triggers for a table are also dropped if you drop the table.

Leave a Comment

MySQL Now() function

NOW()

Returns the current date and time as a value in ‘YYYY-MM-DD HH:MM:SS’ or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone.

mysql> SELECT NOW();
-> ‘2007-12-15 23:50:26′
mysql> SELECT NOW() + 0;
-> 20071215235026.000000

NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13.

mysql> SELECT NOW(), SLEEP(2), NOW();
+———————+———-+———————+
| NOW()               | SLEEP(2) | NOW()               |
+———————+———-+———————+
| 2006-04-12 13:47:36 |        0 | 2006-04-12 13:47:36 |
+———————+———-+———————+

mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE();
+———————+———-+———————+
| SYSDATE()           | SLEEP(2) | SYSDATE()           |
+———————+———-+———————+
| 2006-04-12 13:47:44 |        0 | 2006-04-12 13:47:46 |
+———————+———-+———————+

In addition, the SET TIMESTAMP statement affects the value returned by NOW() but not by SYSDATE(). This means that timestamp settings in the binary log have no effect on invocations of SYSDATE().
See the description for SYSDATE() for additional information about the differences between the two functions.

Leave a Comment

Difference between include, include_once, require, require_once

include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

include()

The include() statement includes and evaluates the specified file.

The documentation below also applies to require(). The two constructs are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well. Be warned that parse error in included file doesn’t cause processing halting in PHP versions prior to PHP 4.3.5. Since this version, it does.

require_once()

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

require()

require() is identical to include() except upon failure it will produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

Example:

Let us create one PHP file and name it as data.php . Here is the content of this file

<?

echo “Hello <br>”; // this will print Hello with one line break

?>

Now let us create one more file and from that we will be including the above data.php file . The name of the file will be inc.php and the code is given below.

<?

include “data.php”; // this will display Hello once

include “data.php”; // this will display Hello once

include “data.php”; // this will display Hello once

include_once “data.php”; // this will not display as the file is already included.

include_once “data.php”; // this will also not display as the file is already included.

?>

So here in the above code the echo command displaying Hello will be displayed three times and not five times. The include_once() command will not include the data.php file again.

Comments (1)

Store images in Database (MySQL)

Instead of storing images as files makes difficult, when moving site to another server, it consumes large space in disk to store as files. So we go for Database. It make simple while moving from one server to another server.

Database design: To store image in MySQL database we need to use blob.

A BLOB is a binary large object that can hold a variable amount of data. The four BLOB types are TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. These differ only in the maximum length of the values they can hold.

CREATE TABLE IF NOT EXISTS `images` (

`Id` int(12) NOT NULL auto_increment,

`Image` longblob NOT NULL,

`mime` varchar(25) NOT NULL,

`type` varchar(4) NOT NULL,

`bits` varchar(10) NOT NULL,

`width` int(11) NOT NULL,

`height` int(11) NOT NULL,

`added` datetime NOT NULL,

`modified` datetime NOT NULL,

PRIMARY KEY (`Id`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1;

PHP code to upload image to DB:

if(is_uploaded_file($ufile['tmp_name']))

{

$imgData =addslashes (file_get_contents($ufile['tmp_name']));

$size = getimagesize($ufile['tmp_name']);

$sql = “INSERT INTO JG_IMAGES (Name,Image,mime,type,width,height,bits,added) VALUES ( ‘{$ufile['name']}’, ‘{$imgData}’, ‘{$size['mime']}’, ‘{$size['2']}’, ‘{$size[0]}’, ‘{$size[1]}’, ‘{$size['bits']}’,now())”;

}

Images are stored in ASCII Format in Database. To show images in page, jus read the data from DB and dump the data to browser with help of header function.

Echo filed data and use below code.

$imgname = $images_row['Image'];
$img = @imagecreatefrompng($imgname);
header(”content-type:image/jpeg;charset=utf-8″);
echo $img;


Leave a Comment

Server side includes

Server Side Includes (SSI) are used to create functions, headers, footers, or elements that will be reused on multiple pages.

Both include() and require() statement includes and evaluates the specific file.

require() and include() are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, don’t hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless.

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script

The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again

require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script

<?php

include ‘file.php’;

require ‘file1.php’;

?>

Leave a Comment

How to create a snapshot of a URL in PHP?

Any one help me how do i create a thumbnail or snapshot of a web page using PHP. I tried HTML to Image, its converting whole html code to an images. I need to create a browser output of a url as a image.

Thanks,

Comments (5)

Sample PHP Codes

Displaying the current date in an HTML page

<? print(Date(“l F d, Y”)); ?>

———————————————————————-

Setting and retrieving a cookie

<?
$check
= “test”;
$check .= $filename;
if (
$test == $check)
{
print(
“<HTML><BODY>You have already voted. Thank you.</BODY></HTML>”);
}
else
{
$rated = “test”;
$rated .= $filename;
setcookie(test, $rated, time()+86400);
print(
“<HTML><BODY><br>You haven’t voted before so I recorded your vote</BODY></HTML>”);
}
?>

Example #1 error_log() examples

bool error_log ( string $message [, int $message_type [, string $destination [, string $extra_headers ]]] )

Sends an error message to the web server’s error log, a TCP port or to a file.

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
error_log(“Oracle database not available!”, 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
error_log(“Big trouble, we’re all out of FOOs!”, 1,
“operator@example.com”);
}

// another way to call error_log():
error_log(“You messed up!”, 3, “/var/tmp/my-errors.log”);
?>

PHP Exception Handling

ith PHP 5 came a new object oriented way of dealing with errors. Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

<?php
//create function with an exception
function checkNum($number)
 {
 if($number>1)
  {
  throw new Exception("Value must be 1 or below");
  }
 return true;
 }

//trigger exception
checkNum(2);
?>

The code above will get an error like this:

Fatal error: Uncaught exception ‘Exception’ with message ‘Value must be 1 or below’ in C:\webfolder\test.php:6 Stack trace: #0 C:\webfolder\test.php(12): checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Try, throw and catch

To avoid the error from the example above, we need to create the proper code to handle an exception.

Proper exception code should include:

  1. Try - A function using an exception should be in a “try” block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is “thrown”
  2. Throw - This is how you trigger an exception. Each “throw” must have at least one “catch”
  3. Catch - A “catch” block retrieves an exception and creates an object containing the exception information

Lets try to trigger an exception with valid code:

<?php
//create function with an exception
function checkNum($number)
 {
 if($number>1)
  {
  throw new Exception("Value must be 1 or below");
  }
 return true;
 }

//trigger exception in a "try" block
try
 {
 checkNum(2);
 //If the exception is thrown, this text will not be shown
 echo 'If you see this, the number is 1 or below';
 }

//catch exception
catch(Exception $e)
 {
 echo 'Message: ' .$e->getMessage();
 }
?>

Leave a Comment

Now Available: Amazon EC2 Running Windows Server

You can now employ Amazon EC2 running Windows Server or SQL Server with all of the performance, reliability, and scalability benefits of Amazon EC2. AWS customers have commonly requested Amazon EC2 running Windows Server and now Amazon EC2 will provide an ideal environment for deploying ASP.NET web sites, high performance computing clusters, media transcoding solutions, and many other Windows-based applications. Like all services offered by AWS, Amazon EC2 running Windows Server or SQL Server offers a low-cost, pay-as-you-go model with no long-term commitments and no minimum fees.

Leave a Comment

Sun Unveils New Systems & Storage Solutions for MySQL

5 November 2008 — Sun Microsystems, Inc. today announced Sun Systems for MySQL™, a set of solutions designed to radically change the economics of Web service delivery for enterprise customers deploying MySQL-based Web Infrastructure on Sun servers. Proven customer deployments have shown the ability to improve performance by 300 percent, reduce power consumption by 83 percent and offer up to 10 times better price/performance, with higher system reliability and faster time to market.

To view a video of John Fowler, executive vice president of Sun’s Systems Group, and Marten Mickos, senior vice president of Sun’s Database Group, discussing the new solutions, please visit: www.sun.com/mysqlsystems.

Leave a Comment

  Domain Name + 1GB Linux India Web Hosting in Rs.349