Tuesday, October 22, 2013

PHP PDO

PHP PDO
PHP PDO with MySQL

What stands for PDO?
The PDO stand for PHP Data Objects (PDO) is an extension defines a lightweight, consistent interface for accessing databases in PHP.

After period of using the older conventional way of accessing database, PDO extension was introduced in July 2004 with PHP5 release. The main reason behind the introduction of this new DB access method seems to be security and the speed. You may find many fact and examples in Internet, so I am not going for further detail and let go the point directly.

Here I am going to concern about MySQL database only. Why? Because as you already know many PHP websites uses MySQL as its database and it is open source. Moreover PHP and MySQL blend together so nicely and many hosting servers also support MySQL.

The connection string to the database is more likely as follows and not to forget include charset parameter to DSN as it is important to avoid any errors occur due to character sets. It is also important for the security.

hostname can either be localhost or your remote MySQL server

$db = new PDO('mysql:host= hostname;dbname=testdb;charset=utf8', 'username', 'password');

There are some optional driver parameters which can pass as an array to the above string or can add separately using setAttribute method.

1. $db = new PDO('mysql:host= hostname;dbname=testdb;charset=utf8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
2. $db = new PDO('mysql:host= hostname;dbname=testdb;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
ATTR_EMULATE_PREPARES need to turned off to use PDO safely and is really only usable if you are using an old version of MySQL.


Error Modes in PDO
  • 1. PDO::ERRMODE_SILENT
  • Same as mysql_* have to check each result and then look at $db->errorInfo(); to get the error details.
  • 2. PDO::ERRMODE_WARNING
  • This mode throws PHP warnings.
  • 3. PDO::ERRMODE_EXCEPTION
  • This mode throws an error type called PDOException. Unless you set it true it acts very much like or die(mysql_error()); in mysql_*. When set to true PDOException can be caught and handled at anywhere. As an example you can catch it inside try catch block after calling to certain DB related function executed.
try {
function db_Operations( );
}
catch (PDOException $ex) {
//show error message to user;
// do_logging($ex->getMessage());
}

PDO Fetch Modes
  • PDO::FETCH_ASSOC: This mode returns an array indexed by column name.
  • PDO::FETCH_BOTH: This mode is the default and returns an array indexed by both column name and 0-indexed column number.
  • PDO::FETCH_BOUND: This mode returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement::bindColumn() method.
  • PDO::FETCH_CLASS: This mode returns a new instance of the requested class, mapping the columns of the result set to named properties in the class. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class is determined from a value of the first column.
  • PDO::FETCH_INTO: This mode updates an existing instance of the requested class, mapping the columns of the result set to named properties in the class
  • PDO::FETCH_LAZY: This mode combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed
  • PDO::FETCH_NUM:
The more info can be found in this link. Now begins the interesting part. To make it more easy and understandable with comparison there is no other way better than implementing them in a table :)

Method Conventional PDO
Select $result = mysql_query('SELECT * from table')
or
die(mysql_error());
$num_rows = mysql_num_rows($result);

while($row = mysql_fetch_assoc($result))
{
echo $row['field1'].' '.$row['field2']; //etc...
}
foreach($db->query('SELECT * FROM table') as $row) {
echo $row['field1'].' '.$row['field2']; //etc...
}
-------------------Or-------------------------------------
$stmt = $db->query('SELECT * FROM table');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'].' '.$row['field2']; //etc...
}
----------or fetch all the result as follows--------------

$stmt = $db->query('SELECT * FROM table');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Insert $results = mysql_query("Insert into table (field1,field2)
VALUES('value1',’value2’)") or
die(mysql_error());

$affected_rows = mysql_affected_rows($result);
echo $affected_rows.' were affected';
$affected_rows = $db->exec("Insert into table (field1,field2)
VALUES('value1',’value2’)");

echo $affected_rows.' were affected'
Update $results = mysql_query("UPDATE table SET field='value'") or die(mysql_error());

$affected_rows = mysql_affected_rows($result);
echo $affected_rows.' were affected';
$affected_rows = $db->exec("UPDATE table SET field='value'");

echo $affected_rows.' were affected'
Delete $results = mysql_query("DELETE from table WHERE field='value'") or die(mysql_error());

$affected_rows = mysql_affected_rows($result);
echo $affected_rows.' were affected';
$affected_rows = $db->exec("DELETE from table WHERE field='value'");

echo $affected_rows.' were affected'
Statements
With
Parameters
$results = mysql_query(sprintf("SELECT * FROM
table WHERE id='%s' AND name='%s'",
mysql_real_escape_string($id), mysql_real_escape_string($name))) or
die(mysql_error());
$rows = array();
while($row = mysql_fetch_assoc($results)){
$rows[] = $row;
}
$stmt = $db->prepare("SELECT * FROM table WHERE id=? AND name=?");

$stmt->execute(array($id, $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Here in the prepare method first sends the query to the server along with ‘?’ place holders where they compiles to be used as expected arguments. Then execute method sends the arguments to the server and runs the compiled statement. This make SQL statement much safer as arguments to be used sends separately to the server which has already compiled statement. So no SQL statement send inside a argument going to execute thus prevents SQL Injections.

Bind Parameter
method
$stmt = $db->prepare("SELECT * FROM table
WHERE id=? AND name=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT)
; $stmt->bindValue(2, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

bindValue() method useful to specify the type for each parameter.

Named Placeholders
(Array)
$stmt = $db->prepare("SELECT * FROM table
WHERE id=:id AND name=:name");
$stmt->execute(array(':name' => $name, ':id' => $id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Name Placeholders
bindValue()
$stmt = $db->prepare("SELECT * FROM table
WHERE id=:id AND name=:name");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Prepared
Insert
$stmt = $db->prepare("INSERT INTO table
(field1,field2,field3) VALUES(:field1,:field2,:field3)");
$stmt->execute(array(':field1' => $field1,
':field2' => $field2, ':field3' => $field3));

$affected_rows = $stmt->rowCount();
Prepared
Update
$stmt = $db->prepare("UPDATE table SET name=? WHERE id=?");
$stmt->execute(array($name, $id));
$affected_rows = $stmt->rowCount();
Prepared Delete $stmt = $db->prepare("DELETE FROM table WHERE id=:id");
$stmt->bindValue(':id', $id, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount();


Correct way to use SQL functions inside PDO.

$name = 'John';
$stmt = $db->prepare("INSERT INTO table(`mod_num`, `name`) VALUES(MOD(7,3), ?)");
$stmt->execute(array($name));

$num1 = 49;
$angle = 30;
$stmt = $db->prepare("INSERT INTO table(`squre_root`, `sine_val`) VALUES(SQRT(?), SIN(?))");
$stmt->execute(array($num1, $angle));

$search='Tom';
$stmt = $db->prepare("SELECT field1 FROM table WHERE field2 LIKE ?");
$stmt->bindValue(1, "%$search%", PDO::PARAM_STR);
$stmt->execute();

Monday, November 2, 2009

Add picture and Information button to the System Properties

Here is the way to do it......
System Properties window appear when you Right click the My Computer Icon

Step 1: Create your own picture having dimension 178x87 pixels or near to that dimensions.
Step 2: Save that image as "oemlogo.bmp" at SystemRoot.
(For Windows NT or above Windows2k save it at "WINDOWS\system32" For Windows 98 at system folder)

Step 3:Create a text file and save it as "oeminfo.ini" at the same path as Step 2.

Step 4:Write in that file following codes.

[General]
Manufacturer=bla bla bla
Model=bla bla bla

[Support Information]
Line1=" "
Line2=" Hi, Dear Friends, Hope U contact me:"
Line3=""
Line4=" name"
Line5=" address1"
Line6=" address2"
Line7=" address3"
Line8=""
Line9=" contact No (voice)"
Line10=""
Line11=""
Line12=" your e-mail"
Line13=" your email"


You can add any number of lines and free to create your own file by changing words inside the double quotation marks.


Step 5: After saving the files (oemlogo.bmp and oeminfo.ini) go to My Comuter Icon
and Right Click that Under the General tab You will the what you created.

Enjoy.

Sunday, November 1, 2009

Installing PHP with Apache as HTTP Server

First, install your selected HTTP (web) server (Like apache) on your system, and
make sure that it works.

Apache httpd.conf file editing for php

For PHP 4:
# Add to the end of the LoadModule section
LoadModule php4_module "c:/php/php4apache.dll"

# Add to the end of the AddModule section
AddModule mod_php4.c

For PHP 5:
# Add to the end of the LoadModule section
LoadModule php5_module "c:/php/php5apache.dll"

# Add to the end of the AddModule section
AddModule mod_php5.c

For both:
# Add this line inside the conditional brace
AddType application/x-httpd-php .php

# For syntax highlighted .phps files, also add
AddType application/x-httpd-php-source .phps


php installation
The following steps should be performed on all installations before the server specific instructions.
• Extract the distribution file to a directory of your choice. "C:\PHP\" is a good start.
The next step is to set up a valid configuration file for PHP, php.ini. There are two ini files distributed in the zip file,
[ php.ini-dist and php.ini-recommended. We advise you to use php.ini-recommended, because we optimized the default settings in this file for performance, and security. Read this well documented file carefully because it has changes from php.ini-dist that will drastically affect your setup. Some examples are display_errors being off and magic_quotes_gpc being off. In addition to reading these, study the ini settings and set every element manually yourself. If you would like to achieve the best security, then this is the way for you, although PHP works fine with these default ini files. Copy your chosen ini-file to a directory that PHP is able to find and rename it to php.ini. PHP searches for php.ini in the following locations (inorder):

* PHPIniDir directive (Apache 2 module only)
* HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath
* The PHPRC environment variable
* Directory of PHP (for CLI), or the web server's directory (for SAPI modules)
* Windows directory (C:\windows or C:\winnt)


If you are running Apache 2, the simpler option is to use the PHPIniDir directive (read the installation on Apache 2 page),otherwise your best option is to set the PHPRC environment variable.This process is explained in the following FAQ entry.
Note: If you're using NTFS on Windows NT, 2000, XP or 2003, make sure that the user running the web server has read permissions to your php.ini (e.g. make it readable by Everyone).
• Copy the file, 'php.ini-dist' to your '%WINDOWS%' directory and rename it to 'php.ini'. Your '%WINDOWS%' directory is typically:
c:\windows for Windows 95/98
c:\winnt or c:\winnt40 for NT servers

Note: In PHP 4, you should move all files located in the dll and sapi folders to the main folder (e.g. C:\php).

php.ini configuration


• You will need to change the 'extension_dir' setting to point to your php-install-dir, or where you have placed your 'php_*.dll' files. ex: c:\php

• If you are using Omni Httpd, do not follow the next step. Set the 'doc_root' to point to your webservers document_root. ex: c:\apache\htdocs or c:\webroot
doc_root = c:\apache\htdocs // for Apache (or wherever your apache installation root htdocs is placed)

• Choose which modules you would like to load when PHP starts. You can uncomment the: 'extension=php_*.dll' lines to load these modules. Some modules require you to have additional libraries installed on your system for the module to work correctly. The PHP FAQ has more information on where to get supporting libraries. You can also load a module dynamically in your script using: dll("php_*.dll");

• On PWS and IIS, you can set the browscap.ini to point to: 'c:\windows\system\inetsrv\browscap.ini' on Windows 95/98 and 'c:\winnt\system32\inetsrv\browscap.ini' on NT Server. Additional information on using the browscap functionality in PHP can be found at this mirror, select the "source" button to see it in action.

Windows Update Troubleshooting

Sometimes due to the infection of viruses you may not be able to update the your genuine version of Windows. Most people use to format and re-install the Windows as soon as they got such kind of problems. But that is not the immediate solution except in a worst case scenario. In fact there are more simple things to do before you decide to re-install of Windows. OK I am not going to explain about these things any further. Lets see how to troubleshoot Windows update problems.

Step 1:

This may due to BITS problem.


Step 2:
You may find at a lot of places in which the word %SystemRoot% had been changed to %fystemRoot% in registry.

Go to Start->Run->type regedit and [ENTER]
search the word fystemRoot (Ctrl+ f)
Go to the ImagePath key and click Modify

If you get an Error saying "Cannot edit ImagePath: Error writing value's new contents."
Right click the folder BITS or Wuaserv (You will most likely have to do both) and select "Permissions..."
Select full control
Go back to the ImagePath key and click Modify again

Change the fystemRoot to SystemRoot at those places.

Check these as well

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Services (BITS and Wuauserv)
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet003\Services (BITS and Wuauserv)
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services (BITS and Wuauserv)