PHP PDO Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

PARAM

PDO::PARAM_BOOL (integer) – Represents a boolean data type.
PDO::PARAM_NULL (integer) – Represents the SQL NULL data type.
PDO::PARAM_INT (integer) – Represents the SQL INTEGER data type.
PDO::PARAM_STR (integer) – Represents the SQL CHAR, VARCHAR, or other string data type.
PDO::PARAM_LOB (integer) – Represents the SQL large object data type.
PDO::PARAM_STMT (integer) – Represents a recordset type. Not currently supported by any drivers.
PDO::PARAM_INPUT_OUTPUT (integer) – Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.

FETCH

PDO::FETCH_LAZY (integer) – Specifies that the fetch method shall return each row as an object with variable names that correspond to the column names returned in the result set.
PDO::FETCH_LAZY – creates the object variable names as they are accessed. Not valid inside PDOStatement::fetchAll().
PDO::FETCH_ASSOC (integer) – Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns only a single value per column name.
PDO::FETCH_NAMED (integer) – Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_NAMED returns an array of values per column name.
PDO::FETCH_NUM (integer) – Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_BOTH (integer) – Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_OBJ (integer) – Specifies that the fetch method shall return each row as an object with property names that correspond to the column names returned in the result set.
PDO::FETCH_BOUND (integer) – Specifies that the fetch method shall return TRUE and assign the values of the columns in the result set to the PHP variables to which they were bound with the PDOStatement::bindParam() or PDOStatement::bindColumn() methods.
PDO::FETCH_COLUMN (integer) – Specifies that the fetch method shall return only a single requested column from the next row in the result set.
PDO::FETCH_CLASS (integer) – Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class. Note: The magic __set() method is called if the property doesn’t exist in the requested class
PDO::FETCH_INTO (integer) – Specifies that the fetch method shall update an existing instance of the requested class, mapping the columns to named properties in the class.
PDO::FETCH_FUNC (integer) – Allows completely customize the way data is treated on the fly (only valid inside PDOStatement::fetchAll()).
PDO::FETCH_GROUP (integer) – Group return by values. Usually combined with PDO::FETCH_COLUMN or PDO::FETCH_KEY_PAIR.
PDO::FETCH_UNIQUE (integer) – Fetch only the unique values.
PDO::FETCH_KEY_PAIR (integer) – Fetch a two-column result into an array where the first column is a key and the second column is the value. Available since PHP 5.2.3.
PDO::FETCH_CLASSTYPE (integer) – Determine the class name from the value of first column.
PDO::FETCH_SERIALIZE (integer) – As PDO::FETCH_INTO but object is provided as a serialized string. Available since PHP 5.1.0. Since PHP 5.3.0 the class constructor is never called if this flag is set.
PDO::FETCH_PROPS_LATE (integer) – Call the constructor before setting properties. Available since PHP 5.2.0.

ATTR

PDO::ATTR_AUTOCOMMIT (integer) – If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.
PDO::ATTR_PREFETCH (integer) – Setting the prefetch size allows you to balance speed against memory usage for your application. Not all database/driver combinations support setting of the prefetch size. A larger prefetch size results in increased performance at the cost of higher memory usage.
PDO::ATTR_TIMEOUT (integer) – Sets the timeout value in seconds for communications with the database.
PDO::ATTR_ERRMODE (integer) – See the Errors and error handling section for more information about this attribute.
PDO::ATTR_SERVER_VERSION (integer) – This is a read only attribute; it will return information about the version of the database server to which PDO is connected.
PDO::ATTR_CLIENT_VERSION (integer) – This is a read only attribute; it will return information about the version of the client libraries that the PDO driver is using.
PDO::ATTR_SERVER_INFO (integer) – This is a read only attribute; it will return some meta information about the database server to which PDO is connected.
PDO::ATTR_CONNECTION_STATUS (integer)
PDO::ATTR_CASE (integer) – Force column names to a specific case specified by the PDO::CASE_* constants.
PDO::ATTR_CURSOR_NAME (integer) – Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.
PDO::ATTR_CURSOR (integer) – Selects the cursor type. PDO currently supports either PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick withPDO::CURSOR_FWDONLY unless you know that you need a scrollable cursor.
PDO::ATTR_DRIVER_NAME (string) – Returns the name of the driver.
PDO::ATTR_ORACLE_NULLS (integer) – Convert empty strings to SQL NULL values on data fetches.
PDO::ATTR_PERSISTENT (integer) – Request a persistent connection, rather than creating a new connection. See Connections and Connection management for more information on this attribute.
PDO::ATTR_STATEMENT_CLASS (integer)
PDO::ATTR_FETCH_CATALOG_NAMES (integer) – Prepend the containing catalog name to each column name returned in the result set. The catalog name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
PDO::ATTR_FETCH_TABLE_NAMES (integer) – Prepend the containing table name to each column name returned in the result set. The table name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
PDO::ATTR_STRINGIFY_FETCHES (integer)
PDO::ATTR_MAX_COLUMN_LEN (integer)
PDO::ATTR_DEFAULT_FETCH_MODE (integer) – Available since PHP 5.2.0
PDO::ATTR_EMULATE_PREPARES (integer) – Available since PHP 5.1.3.

ERRMODE

PDO::ERRMODE_SILENT (integer) – Do not raise an error or exception if an error occurs. The developer is expected to explicitly check for errors. This is the default mode. See Errors and error handling for more information about this attribute.
PDO::ERRMODE_WARNING (integer) – Issue a PHP E_WARNING message if an error occurs. See Errors and error handling for more information about this attribute.
PDO::ERRMODE_EXCEPTION (integer) – Throw a PDOException if an error occurs. See Errors and error handling for more information about this attribute.
PDO::ERR_NONE (string) – Corresponds to SQLSTATE ‘00000’, meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.

CASE

PDO::CASE_NATURAL (integer) – Leave column names as returned by the database driver.
PDO::CASE_LOWER (integer) – Force column names to lower case.
PDO::CASE_UPPER (integer) – Force column names to upper case.

Sumber: PHP.Net

Ubuntu 14.04 on VirtualBox

Alhamdulillah. Cuti yang banyak pada bulan Februari ini memberi peluang untuk menambahkan lagi ilmu mengenai Sistem Operasi berasaskan Unix. Sistem Operasi Ubuntu Desktop 14.04 telah dipilih memandangkan ia lebih user friendly (ala-ala windows deskop). Memandangkan saya hanya ingin belajar untuk pemasangan dan penggunaan sistem operasi ini secara asas serta beberapa aplikasi lain yang terdapat dalam ubuntuk, jadi saya menggunakan VirtualBox sebagai tools untuk mencipta sistem operasi secara virtual.

Pemasangan Sistem Operasi Ubuntu Desktop 14.04 ini amat mudah. Terutama dengan tutorial yang sedia ada dalam Komuniti Ubuntu; sangat membantu. Tapi sebelum ini kita perlu memasang VirtualBox. Juga terdapat banyak tutorial pemasangan dan penetapan yang boleh digunakan semasa pemasangan. Untuk komputer saya dengan spesifikasi di bawah:

pc

 

Proses pemasangan tidak menjadi masalah besar. Cuma saya menghadkan sumber (ruang HDD dan RAM) agar penggunaannya tidak keterlaluan. Berikut setting yang telah ditetapkan setelah sistem operasi ini berjaya dipasang di virtualbox:

vbox

 

Setelah pemasangan sistem operasi berjaya. Perkara pertama bermain difikiran saya adalah bagaimana untuk memasang web server (LAMP – linux, apache2, mysql dan php) ke dalam ubuntu desktop ini. Dengan mengikut tutorial seperti video di youtube ini, akhirnya saya berjaya┬ámemasangan aplikasi apache, php,┬ámysql, phpmyadmin dan wordpress. Melalui video ini juga saya belajar menetapkan pengguna dan permission untuk pengguna tadi. Satu yang saya tertarik dalam video ini adalah┬áproses┬ámemasang┬áWebmin.

Insyallah lepas ini, akan banyak lagi penerokaan pada Sistem Operasi Ubuntu Desktop 14.04 ini akan dilakukan.

Jom PDO

Memandangkan sekarang kita sudah mula menggunakan PHP dan kaedah PDO untuk berinteraksi dengan pengkalan data mySQL serta ada kawan-kawan yang bertanya mengenai PDO, jadi saya akan buat satu tutorial ringkas procedural PHP dan PDO untuk pengkalan data mySQL. Sebelum itu untum rujukan mengenai PDO, sila rujuk artikel MySQLi vs PDO.

Contoh kod sambungan ke pengkalan data:

<?php
try {
$conn = new PDO(‘mysql:host=localhost;dbname=datasaya’, “root”, “abc123”);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
}
catch(PDOException $e) {
die(‘ERROR: ‘ . $e->getMessage());
}
?>

Code di atas adalah untuk membuat sambungan ke pengkalan data mySQL dengan datasaya adalah nama pengkalan data, root adalah pengguna pengkalan data dan abc123 adalah katalaluan pengguna pengkalan data.

Contoh kod untuk tambah data:

<?php
$s = “INSERT INTO pengguna┬áSET┬ánama┬á= :nama, katalaluan = :pass”;
$q = $conn->prepare($s);
$q->execute(array(
‘nama’ => $_POST[‘nama’],
‘pass’ => $_POST[‘pass’]
));
?>

Kod di atas akan menambah nilai yang dibawa melalui kaedah $_POST iaitu nama dan pass ke dalam pengkalan data.

Contoh kod untuk memilih data:

<?php
$s = “SELECT┬á* FROM┬ápengguna WHERE┬ánama LIKE :nama”;
$q = $conn->prepare($s);
$q->execute(array(
‘nama’ => ‘%’.$_POST[‘nama’].’%’
));
?>

Kod di atas akan memilih data dimana field nama pengkalan datanya adalah yang berpadan dengan nilai yang dihantar melalui kaedah $_POST tersebut

Contoh kod untuk mengubah data:

<?php
$s = “UPDATE┬ápengguna┬áSET┬ánama┬á= :nama WHERE id┬á= :id”;
$q = $conn->prepare($s);
$q->execute(array(
‘nama’ => $_POST[‘nama’],
‘id’ => $_POST[‘id’]
));
?>

Kod ini pula adalah untuk mengemaskini maklumat data kepada nilai nama yang baru untuk pengguna id berkenaan

Contoh kod untuk menghapus data:

<?php
$s = “DELETE FROM┬ápengguna WHERE id┬á= :id”;
$q = $conn->prepare($s);
$q->execute(array(
‘id’ => $_POST[‘id’]
));
?>

Dan kod ini pula adalah untuk menghapus data bagi id pengguna berkenaan

Jadi setakat ini dulu asas kepada pengaturcaraan PHP menggunakan kaedah PDO untuk berinteraksi dengan mySQL.

Currently and mission…

Maaf lama tidak menghantar tutorial! Jadi, apa yang saya sedang lakukan pada waktu ini?

1) Membangunkan Portal eLearning Psikiatri
2) Membangunkan Sistem MealPlan
3) Mengemaskini Portal Aktiviti
4) Mengajar PHP & mySQL : Basic to Intermediate (insyallah)

Dan masih terus menambah ilmu mengenai:

1) Laravel 4.2
2) Sublime Text 3
3) Git 1.9.4
4) PHP 5.5.15 (will upgade to 5.6 later)

Insyallah…

GIT – Distributed Version Control and Source Code Management (SCM) System

Introduction To GIT

  1. Abstract
  2. Creating a Repository
  3. Checking Out A Repository
  4. Add And Commit
  5. Pushing Changes
  6. Branches
  7. Update and Merge
  8. Tagging
  9. Revert To Specifit Commit

Abstract

GIT is a distributed version control and source code management (SCM) system developed by by Linus Torvalds for Linux kernel development, Git has since been adopted as the choice of source code management by many projects and companies. This document covers the creation, usage and management of the GIT versioning system.

The installation of GIT is beyond the scope of this tutorial, however, here are some links that will help

 

Creating a Repository

To create a repository for your project, select a place where you have write privileges. For our purposes here, we will create a repository for a project name ACL. So lets begin with creating the repository(repo).

mkdir ~/git_repos
mkdir ~/git_repos/acl
cd ~/git_repos/acl
git init

The above commands will firstly create a directory name .git in which, in turn, will contain some directories and files need to work with the GIT system. A quick look inside the .git directory shows us the following

# ls ~/git_repos/acl/.git
branches config description HEAD hooks info objects refs

Checking Out A Repostiory

If you are using a local repository, checking out a copy is as simple as:

git clone ~/git_repos/acl

If you are checking out a remote repository, then use this command.

git clone username@hostname:/home/kevin/git_repos/acl

The local repository consists of three “trees” maintained by git

Working Directory
Contains the acutal files
Index
Acts as a staging area
HEAD
Points to the last commit

The workflow will look like this.

WORKING DIR -> add -> INDEX -> commit -> HEAD

Add And Commit

When you add a file to GIT, the addition is stored as a proposed changed, which means it is stored in the Index. To add a file named acl.php is as simple as:

git add acl.php

If you had multiple files you wanted to add, you can use the command

git add *

Currently the file is just a proposed addition, and not commited to the repository. To commit we use git commit.

git commit -m “Message to say I added acl.php file”

The acl.php is now in HEAD, but not yet in the remote repository repository. Any additions and changes need to be pushed to the remote repository before they are available to all.

Pushing Changes

To push changes to the remote repository, the git push command is used.

git push origin master

The master can be whatever branch you want to push the changes to.

Thats IT!?. Yup, thats it

If you have not cloned an existing repository and want to connect your repository to a remote server, you need this command

git remote add origin server_name

Now you are able to push your changes to the selected remote server

Branches

Branches are used to develop features in isolation. The master branch is the “default” branch when you create a repository. Use other branches for development and merge them back to the master branch upon completion.

The workflow will look like this..

           ---------- Feature ----------
          |                            |
          |                            |
--------------------- Master -------------------------
       branch                        merge

So, to create a branch called my_feature_branch, and switch directly to it

git checkout -b my_feature_branch

You should see a message like

Switched to a new branch ‘my_feature_branch’

Now, to switch back to master brach

git checkout master
Switched to branch ‘master’

A local branch is not available to others, as it is not yet in the repository. The branch needs to be pushed to the remote repository to be available to all.

git push origin my_feature_branch

And finally, to delete the branch, we use the -d switch

git branch -d my_feature_branch
Deleted branch my_feature_branch (was b37035b).

Update and Merge

Of course, you are not the only person using the repository. Others will commit changes and you need to keep your local copy up to date by pulling new changes from the remote repository. To do so, use the pull command. This will both pull and merge changes from the remote repo, into your local copy.

git pull

To merge another branch into your active branch eg: master, use this command.

git merge my_feature_branch

When git pulls from the remote repository, or merges a branch, it tries to auto-merge the content. Inevitably, there are conflicts. You are responsible to merge those conflicts manually by editing the files shown by git. After changing, you need to mark them as merged. Using:

git add

Some of these conflicts can be avoided by checking for conflicts before merging with git diff

git diff source_branch target_branch

`

Tagging

Tagging a release is a great idea for tracking releases and milestones in a project. Those who are familiar with SVN would be familiar with this concept. To create a new tag, first use the git log command to get the last commit ID and then use git tag with the ID you just gained.

git log
commit b37035b424c82dd1b4baee3b8184ddbead32edd0
Author: Kevin Waterson <kevin@jyotish.(none)>
Date: Fri Jul 5 09:37:27 2013 +1000git tag 1.0.0 b37035b424c82dd1b4baee3b8184ddbead32edd0

Another simple way to use a an annotated tag in GIT, which is really just a pointer to the current commit is this. This example assumes a tag for a release of version 37 of a project.

git tag -a v37 -m ‘Release 37’

Revert To Specifit Commit

Sometimes you need to revert or rollback to a specific commit. Here we show how to revert back to commit id 296b09c

git reset 296b09c
git reset –soft HEAD@{1}
git commit -m “Revert message to tell you have reverted”
git reset –hard

MySQLi vs PDO

Seperti semua sedia maklum, versi PHP terkini adalah 5.5.7. Antara isu yang dibangkitkan oleh segelintir programmer adalah fungsi mysql_* yang telah dideprecated mulai PHP 5.5.0. Jadi walaupun kita masih menggunakan server yang menggunakan versi PHP sebelum 5.5.0, adalah disarankan agar kita menukar fungsi mysql_* kita kepada fungsi MySQLi atau PDO.

Kedua-dua fungsi ini mempunyai persamaan dan perbezaan yang tidak terlalu ketara. Dengan adanya fungsi-fungsi ini, konsep prepared statements, multiple statements dan transactions dapat digunakan dengan lebih mudah dan berkesan. Selain itu, pada fungsi mysql_*, fungsi mysql_real_escape_string dan concatenating biasanya ditentukan oleh programmer itu sendiri. Ini adalah amat berbahaya kepada sistem yang hendak dibangunkan kerana mudah terdedah kepada SQL Injection.


MySQLi

MySQLi Extension (mysql improved) membolehkan kita mengakses fungsi yang terdapat pada MySQL versi 4.1.13 ke atas. MySQLi adalah versi yang lebih baik berbanding MySQL sebelumnya. Terdapat banyak fungsi baru yang ada boleh kita gunakan.

MySQLi biasanya menggunakan OOP (Object-Oriented Programming) tetapi kita masih boleh menggunakan procedural programming.

Contoh OOP dalam MySQLi:

$conn = new mysqli(“localhost”, “root”, “”, “database”);
if ($conn->connect_error) {
die(‘Database connection failed: ‘.$conn->connect_error, E_USER_ERROR);
}

Contoh Procedural API:

$conn = mysqli_connect(“localhost”, “root”, “”, “database”);
if (mysqli_connect_errno()) {
die(‘Database connection failed: ‘.mysqli_connect_error(), E_USER_ERROR);
}

Sumber:
+ W3Schools
+ Pontikis.net


PDO

Selain MySQLi, PDO (PHP Data Object) juga adalah satu lagi pilihan yang adalah untuk berinteraksi dengan MySQL. Berbanding dengan MySQLi, PDO hanya ditulis menggunakan OOP. Kod-kod yang ditulis menggunakan PDO biasanya lebih selamat dan kemas.

Berbeza dengan MySQLi yang hanya boleh berinterasi dengan MySQL, PDO boleh berinteraksi dengan banya database. Selain daripada MySQL, PDO boleh berinteraksi dengan IBM, Informix, ODBC, PostgreSQL, SQLite, Oracle dan sebagainya.

PDO juga mempunyai banyak kaedah error handling. Dalam PDO, exception mode membolehkan anda mengetahui ralat (error) dengan lebih konsisten dan ini membantu anda untuk menangani isu-isu tadi dengan lebih cepat dan mudah.

Contoh PDO:

$conn = new PDO(‘mysql:host=localhost;dbname=database;charset=utf8’, ‘root’, ”);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Sumber:
+ HashPHP.Org
+ TutPlus.Com


Apakah Prepared Statements dan Kenapa Ia Penting?

Prepared statements adalah fungsi yang lazim digunakan pada MySQLi dan PDO. Andaikan kita mempunyai satu string yang mempunyai simbol ‘ (single quote). Cthnya, “Pak Mat’s House”. Di dalam MySQL, kita perlu menggunakan fungsi real_escape_string(). Tetapi menggunakan MySQLi atau PDO, kita hanya perlu gunakan fungsi prepare(). Kebiasannya, melalui fungsi ini sql statement datatype akan ditentukan melalui fungsi bind_param (MySQLi) atau bindParam (PDO) sebelum di proses (melalui fungsi excute()).

Contoh MySQLi:

$sql = ‘SELECT field FROM table WHERE field = ? ‘;
$data = ‘Pak Mat’ House’;
$stmt = $conn->prepare($sql);
/* Bind parameters. TYpes: s = string, i = integer, d = double,  b = blob */
$stmt->bind_param(‘s’,$data);
$stmt->execute();

Contoh PDO:

$sql = ‘SELECT field FROM table WHERE field = :field’;
$data = ‘Pak Mat’ House’;
$stmt = $conn->prepare($sql);
$stmt->bindParam(‘:field’, $data, PDO::PARAM_STR);
$stmt->execute();

Jadi kita perhatikan disini, user input akan difilter terlebih dahulu sebelum diproses. Ini akan menjadikan query kita lebih selamat. Fungsi di atas juga amat efektif (performance increase) sekiranya kita membuat sql statement berulang-ulang kali.

Kedua-duanya mempunyai kelebihan dan kekurangan sendiri. Ada juga pertanyaan manakah yang lebih bagus. Saya menjawab bergantung kepada citarasa masing-masing yang mana lebih anda suka :). Tapi sekiranya ada kemungkinan aplikasi itu menggunakan multiple database (cth MySQL, Oracle, IBM), jadi PDO adalah pilihan paling tepat. Saya sendiri menyarankan menggunakan PDO meskipun anda hanya menggunakan MySQL.

Apa itu DDL, DML dan DCL?

Secara asasnya, arahan SQL boleh dibahagikan kepada 3 kumpulan kecil iaitu DDL, DML and DCL.

DDL

DDL adalah singkatan dari Data Definition Language yang  menerangkan bagaimana data boleh disimpan dalam pengkalan data melalui skema dan keterangan pengkalan data yang ditetapkan.

  • CREATE – untuk mencipta pengkalan data
  • ALTER – mengubah struktur pengkalan data
  • DROP – menghapuskan pengkalan data
  • TRUNCATE – menghapuskan semua rekod yang ada dalam table pengkalan data
  • COMMENT – menambah komen data dictionary
  • RENAME – menukar nama pengkalan data

DML

DML pula adalah singkatan kepada Data Manipulation Language yang mana ia adalah berkaitan dengan manipulasi data. Kebiasaannya, DML adalah berkaitan dengan pernyataan SQL seperti SELECT, INSERT, UPDATE, DELETE dan sebagainya. Pernyataan-pernyataan ini digunakan untuk menyimpan, mengubah, menyenarai (retrieve), menghapus dan mengemaskini data di dalam sesuatu pengkalan data

  • SELECT – retrieve data dari pengkalan data
  • INSERT – menambah data ke dalam sesuatu table
  • UPDATE – mengemaskini data sedia ada di dalam sesuatu table
  • DELETE – menghapuskan rekod di dalam table sesuatu pengkalan data
  • MERGE – UPSERT operation (insert or update)
  • CALL – call a PL/SQL or Java subprogram
  • EXPLAIN PLAN – interpretation of the data access path
  • LOCK TABLE – concurrency Control

DCL

Manakala DCL pula adalah singkatan untuk Data Control Language dan berfungsi untuk melakukan arahan seperti GRANT; kebiasaannya untuk arahan rights, permissions dan kawalan lain sistem pengkalan data

  • GRANT – membenarkan pengguna mempunyai akses terhadap sesuatu pengkalan data
  • REVOKE – menarik balik kebenaran akses yang telah diberi melalui arahan GRANT tadi