Keselamatan Siber: Open Source bukan punca kelemahan keselamatan siber

Keselamatan Siber

BARU-BARU ini, terdapat laporan akhbar yang menyalahkan penggunaan Perisian Sumber Terbuka atau Open Source Software (OSS) sebagai salah satu punca laman web digodam.

Di sini, saya ingin menjelaskan apa sumbangan Perisian Terbuka ini kepada pembangunan teknologi maklumat.

Perisian Sumber Terbuka atau Open Source Software (OSS), adalah hasil daripada satu amalan bersifat sukarela dan gotong royong.

Ia adalah usaha untuk memastikan tiada siapa yang memiliki perisian dengan lesen yang hadkan penggunaan dan kenakan kos yang tidak berpatutan kepada penggunaan.

Ia bertujuan untuk memastikan perisian yang dibangunkan dapat dikongsikan pembangunan dan disebarkan tanpa kerisauan kepada milikan dan juga kos lesen.

Untuk memastikan prinsip ini berterusan dan sah disisi undang-undang, komuniti Sumber Terbuka melalui Open Source Initiative (OSI) iaitu satu organisasi antarabangsa, menyediakan platform untuk menjamin semua perisian sumber terbuka mempunyai lesen yang bersifat terbuka dan boleh diguna pakai oleh pelbagai pihak sama ada individu, organisasi bukan kerajaan, syarikat-syarikat dan kerajaan.

Usaha ini telah berlaku sejak Februari 1998, lebih 20 tahun perlesenan sumber terbuka dan usaha secara komuniti, sukarela dan gotong royong ini dilakukan, malah ia terus semakin kuat dan berterusan dengan sokongan pelbagai pihak dan syarikat yang menerima manfaat yang besar daripada segi kewangan dan juga faedah-faedah lain.

Lebih 20 tahun sejak 1998, perisian sumber terbuka telah menjadi tulang belakang industri ICT dunia seiring dengan keselamatan siber yang mengikuti rapat perisian sumber terbuka.

Terlalu banyak untuk disenaraikan daripada dahulu hingga sekarang pada setiap perisian sumber terbuka yang dibangunkan; daripada compiler C yang menjadi asas pembangunan kepada pelbagai lagi perisian sumber terbuka sehinggalah kepada Kernel Linux yang menjadi asas kepada perisian komputer-komputer dan peralatan rangkaian yang menjalankan internet dan juga perisian Android yang kuasakan telefon bimbit yang kita gunakan.

Kebanyakan syarikat-syarikat besar sekarang ini adalah berasas teknologi yang dibina atas perisian sumber terbuka. Bermula dengan syarikat Red Hat, yang pada awalnya mahu memudahkan pemasangan sistem operasi untuk komputer dan kemudiannya menjadi syarikat ‘Bilion Dolar’ yang kemudian dibeli oleh IBM, gergasi ICT dunia.

Google merupakan penyokong kuat kepada perisian sumber terbuka sejak daripada penubuhannya lagi.

Komputer-komputer yang menyokong infrastuktur Google dalam menjalankan perniagaan enjin carian yang dibina atas perisian sumber terbuka, kini berkembang penggunaan di seluruh dunia.

Google menjadi gergasi industri ICT dengan perisian sumber terbuka, begitu juga dengan Facebook, yang mula dibangunkan dengan perisian sumber terbuka PHP.

PHP adalah bahasa atur cara yang menjalankan Facebook malah ribuan laman-laman web seluruh dunia. Ia sungguh popular hingga sebarang isu keselamatan yang berlaku terasa bagai ia satu kelemahan PHP, sedangkan ia disebabkan oleh ralat yang berlaku kerana pembangunan perisian dengan cara amalan yang tidak selamat dan cekap.

Ia juga disebabkan tiada tindakan segera untuk membetulkan ralat.

Kerajaan Malaysia melalui agensi Unit Pemodenan Tadbiran Dan Perancangan Pengurusan Malaysia (MAMPU) dan juga CyberSecurity Malaysia (CSM) turut menyediakan program latihan khusus untuk pegawai-pegawai ICT dalam kerajaan dalam penggunaan Perisian Sumber Terbuka dan Keselamatan Siber.

Ia menjadi keperluan kepada kerajaan kerana penggunaan luas perisian sumber terbuka dan menangani masalah keselamatan siber dalam pelbagai kemudahan dan perkhidmatan ICT kerajaan Malaysia.

Ia harus dikekal peranan dan berterusan untuk melatih dan melahirkan kakitangan ICT yang setaraf, berkemahiran tinggi dan bekemampuan mengendalikan perisian sumber terbuka dan keselamatan kod serta aplikasi.

Tidak dapat dinafikan ada laman-laman web yang bocor atau ditembusi, namun kita perlu lihat dalam pandangan yang lebih luas, dalam beribu-ribu laman web, dengan ratusan laman-laman web perkhidmatan utama, semuanya dapat dipertahankan dan tiada isu-isu keselamatan.

Sebahagian kecil laman-laman web yang tembus apabila diperiksa semula adalah laman-laman web yang tidak penting atau perkhidmatan dalam peringkat untuk ditamatkan.

Malah ada juga yang sedang dalam usaha pembaikan, hanya keadaan tidak kesempatan pada masanya disebabkan isu isu tertentu.

Tiada mana mana aplikasi sumber terbuka yang 100 peratus bebas dari ancaman siber tetapi harus diingatkan bahawa kesedaran dalam menguruskan aplikasi sumber terbuka ini harus menjadi perkara yang utama iaitu “Update, Patching, Maintenance & Support (UPMS)” kerana ia saling berkait antara satu sama lain.

Ia harus berterusan dan tidak ditinggalkan separuh jalan hanya kerana mungkin disebabkan ramai beranggapan perisian sumber terbuka adalah percuma dan FOC  tetapi tidak bagi servisnya yang perlu disediakan bajet yang sepatutnya.

Kami dalam Industri ICT sama ada individu, swasta dan juga kerajaan, sentiasa berusaha untuk memastikan perkhidmatan ICT dan Internet Malaysia ini sentiasa dalam keadaan selamat dan dikemas kini.

Perisian Sumber Terbuka dan Keselamatan Siber  komuniti-komunitinya adalah satu usaha sukarela. Ia dilakukan dengan bertujuan untuk kebaikan untuk semua.

Tanpanya kita semua tidak akan dapat perkhidmatan yang canggih dan maju seperti sekarang ini.

Harisfazillah Jamel & Mohd Fazli Azran
Komuniti Sumber Terbuka Malaysia & Komuniti Keselamatan Siber

Sumber: AstroAwani

PHP 7.4 Upgrade Notes

PHP 7.4 Upgrade Notes

1. Backward Incompatible Changes
2. New Features
3. Changes in SAPI modules
4. Deprecated Functionality
5. Changed Functions
6. New Functions
7. New Classes and Interfaces
8. Removed Extensions and SAPIs
9. Other Changes to Extensions
10. New Global Constants
11. Changes to INI File Handling
12. Windows Support
13. Migration to pkg-config
14. Other Changes
15. Performance Improvements

========================================
1. Backward Incompatible Changes
========================================

– Core:
. Trying to use values of type null, bool, int, float or resource as an
array (such as $null[“key”]) will now generate a notice. This does not
affect array accesses performed by list().
RFC: https://wiki.php.net/rfc/notice-for-non-valid-array-container
. get_declared_classes() no longer returns anonymous classes that haven’t
been instantiated yet.
. “fn” is now a reserved keyword. In particular it can no longer be used as a
function or class name. It can still be used as a method or class constant
name.
. Passing the result of a (non-reference) list() assignment by reference is
consistently disallowed now. Previously this worked if the right hand side
was a simple (CV) variable and did not occur as part of the list().
. `<?php` at the end of the file (without trailing newline) will now be
interpreted as an opening PHP tag. Previously it was interpreted either as
`<? php` and resulted in a syntax error (with short_open_tag=1) or was
interpreted as a literal `<?php` string (with short_open_tag=0).
. When using include/require on a stream, stream_set_option() will be invoked
with the STREAM_OPTION_READ_BUFFER option. Custom stream wrapper
implementations may need to implement the stream_set_option() method to
avoid a warning (always returning false is a sufficient implementation).

– BCMath:
. BCMath functions will now warn if a non well-formed number is passed, such
as “32foo”. The argument will be interpreted as zero (as before).

– Curl:
. Attempting to serialize a CURLFile class will now generate an exception.
Previously the exception was only thrown on unserialization.
. Using CURLPIPE_HTTP1 is deprecated, and is no longer supported as of cURL
7.62.0.
. The $version parameter of curl_version() is deprecated. If any value not
equal to the default CURLVERSION_NOW is passed, a warning is raised and the
parameter is ignored.

– Date:
. Calling var_dump() or similar on a DateTime(Immutable) instance will no
longer leave behind accessible properties on the object.
. Comparison of DateInterval objects (using ==, < and so on) will now generate
a warning and always return false. Previously all DateInterval objects were
considered equal, unless they had properties.

– Intl:
. The default parameter value of idn_to_ascii() and idn_to_utf8() is now
INTL_IDNA_VARIANT_UTS46 instead of the deprecated INTL_IDNA_VARIANT_2003.

– MySQLi:
. The embedded server functionality has been removed. It was broken since
at least PHP 7.0.
. The undocumented mysqli::$stat property has been removed in favor of
mysqli::stat().

– Openssl:
. The openssl_random_pseudo_bytes() function will now throw an exception in
error situations, similar to random_bytes(). In particular, an Error is
thrown if the number of requested bytes is less than *or equal to* zero,
and an Exception is thrown if sufficient randomness cannot be gathered.
The $crypto_strong output argument is guaranteed to always be true if the
function does not throw, so explicitly checking it is not necessary.
RFC: http://php.net/manual/de/function.openssl-random-pseudo-bytes.php

– PCRE:
. When PREG_UNMATCHED_AS_NULL mode is used, trailing unmatched capturing
groups will now also be set to null (or [null, -1] if offset capture is
enabled). This means that the size of the $matches will always be the same.

– PEAR:
. Installation of PEAR (including PECL) is no longer enabled by default. It
can be explicitly enabled using –with-pear. This option is deprecated and
may be removed in the future.

– PDO:
. Attempting to serialize a PDO or PDOStatement instance will now generate
an Exception rather than a PDOException, consistent with other internal
classes which do not support serialization.

– Reflection:
. Reflection objects will now generate an exception if an attempt is made
to serialize them. Serialization for reflection objects was never
supported and resulted in corrupted reflection objects. It has been
explicitly prohibited now.

– SPL:
. Calling get_object_vars() on an ArrayObject instance will now always return
the properties of the ArrayObject itself (or a subclass). Previously it
returned the values of the wrapped array/object unless the STD_PROP_LIST
flag was specified. Other affected operations are:

* ReflectionObject::getProperties()
* reset(), current(), etc. Use Iterator methods instead.
* Potentially others working on object properties as a list.

(array) casts are *not* affected. They will continue to return either the
wrapped array, or the ArrayObject properties, depending on whether the
STD_PROP_LIST flag is used.
. SplPriorityQueue::setExtractFlags() will throw an exception if zero is
passed. Previously this would generate a recoverable fatal error on the
next extraction operation.
. ArrayObject, ArrayIterator, SplDoublyLinkedList and SplObjectStorage now
support the __serialize() + __unserialize() mechanism in addition to the
Serializable interface. This means that serialization payloads created on
older PHP versions can still be unserialized, but new payloads created by
PHP 7.4 will not be understood by older versions.

– Standard:
. The “o” serialization format has been removed. As it is never produced by
PHP, this may only break unserialization of manually crafted strings.
. Password hashing algorithm identifiers are now nullable strings rather
than integers.

* PASSWORD_DEFAULT was int 1; now is null
* PASSWORD_BCRYPT was int 1; now is string ‘2y’
* PASSWORD_ARGON2I was int 2; now is string ‘argon2i’
* PASSWORD_ARGON2ID was int 3; now is string ‘argon2id’

Applications correctly using the constants PASSWORD_DEFAULT,
PASSWORD_BCRYPT, PASSWORD_ARGON2I, and PASSWORD_ARGON2ID will continue to
function correctly.
. htmlentities() will now throw a notice (instead of a strict standards
warning) if it is used with an encoding for which only basic entity
substitution is supported, in which case it is equivalent to
htmlspecialchars().
. fread() and fwrite() will now return false if the operation failed.
Previously an empty string or 0 was returned. EAGAIN/EWOULDBLOCK are not
considered failures.
. fread() and fwrite() on plain files will now throw a notice on failure,
such as when trying to write to a read-only file resource.

– Tokenizer:
. token_get_all() will now emit a T_BAD_CHARACTER token for unexpected
characters instead of leaving behind holes in the token stream.

========================================
2. New Features
========================================

– Core:
. Added support for typed properties. For example:

class User {
public int $id;
public string $name;
}

This will enforce that $user->id can only be assigned integers and
$user->name can only be assigned strings. For more information see the
RFC: https://wiki.php.net/rfc/typed_properties_v2

. Added support for arrow functions with implicit by-value scope binding.
For example:

$factor = 10;
$nums = array_map(fn($num) => $num * $factor, $nums);

RFC: https://wiki.php.net/rfc/arrow_functions_v2

. Added support for limited return type covariance and argument type
contravariance. The following code will now work:

class A {}
class B extends A {}

class Producer {
public function method(): A {}
}
class ChildProducer extends Producer {
public function method(): B {}
}

Full variance support is only available if autoloading is used. Inside a
single file only non-cyclic type references are possible, because all
classes need to be available before they are referenced.
RFC: https://wiki.php.net/rfc/covariant-returns-and-contravariant-parameters

. Added support for coalesce assign (??=) operator. For example:

$array[‘key’] ??= computeDefault();
// is roughly equivalent to
if (!isset($array[‘key’])) {
$array[‘key’] = computeDefault();
}

RFC: https://wiki.php.net/rfc/null_coalesce_equal_operator

. Added support for unpacking inside arrays. For example:

$arr1 = [3, 4];
$arr2 = [1, 2, …$arr1, 5];
// $arr2 == [1, 2, 3, 4, 5]

RFC: https://wiki.php.net/rfc/spread_operator_for_array

. Added support for underscore separators in numeric literals. Some examples:

6.674_083e-11; // float
299_792_458; // decimal
0xCAFE_F00D; // hexadecimal
0b0101_1111; // binary

RFC: https://wiki.php.net/rfc/numeric_literal_separator

. Support for WeakReferences has been added.
RFC: https://wiki.php.net/rfc/weakrefs

. Throwing exceptions from __toString() is now permitted. Previously this
resulted in a fatal error. Existing recoverable fatals in string conversions
have been converted to Error exceptions.
RFC: https://wiki.php.net/rfc/tostring_exceptions

– CURL:
. CURLFile now supports stream wrappers in addition to plain file names, if
the extension has been built against libcurl >= 7.56.0. The streams may
need to be seekable.

– Filter:
. The FILTER_VALIDATE_FLOAT filter now supports the min_range and max_range
options, with the same semantics as FILTER_VALIDATE_INT.

– FFI:
. A new extension which provides a simple way to call native functions, access
native variables and create/access data structures defined in C libraries.
RFC: https://wiki.php.net/rfc/ffi

– GD:
. Added the “scatter” image filter (IMG_FILTER_SCATTER) to apply a scatter
filter to images. This filter has the following prototype:

imagefilter($im, IMG_FILTER_SCATTER, int $sub, int $plus, array $colors = []);

The $colors array can be populated with a set of indexed colors to
apply the scatter pixel shifting on.

Note, the result of this filter is always random.

– Hash:
. Added “crc32c” hash using Castagnoli’s polynomial. This crc32 variant is
used by storage systems, such as iSCSI, SCTP, Btrfs and ext4.

– Mbstring:
. Added mb_str_split() function, which provides the same functionality as
str_split(), but operating on code points rather than bytes.
RFC: https://wiki.php.net/rfc/mb_str_split

– OPcache:
. Support for preloading code has been added.
RFC: https://wiki.php.net/rfc/preload

– PCRE:
. The preg_replace_callback() and preg_replace_callback_array() functions now
accept an additional $flags argument, with support for the
PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags. This influences the
format of the matches array passed to to the callback function.

– PDO:
. The username and password can now be specified as part of the PDO DSN for
the mysql, mssql, sybase, dblib, firebird and oci drivers. Previously this
was only supported by the pgsql driver. If a username/password is specified
both in the constructor and the DSN, the constructor takes precedence.

new PDO(“mysql:host=xxx;port=xxx;dbname=xxx;user=xxx;password=xxx”);

– PDO_OCI:
. PDOStatement::getColumnMeta() is now available

– PDO_SQLite:
. PDOStatement::getAttribute(PDO::SQLITE_ATTR_READONLY_STATEMENT) allows
checking whether the statement is read-only, i.e. if it doesn’t modify
the database.
. PDO::setAttribute(PDO::SQLITE_ATTR_EXTENDED_RESULT_CODES, true) enables the
use of SQLite3 extended result codes in errorInfo().

– SQLite3:
. Added SQLite3::lastExtendedErrorCode() to fetch the last extended result
code.
. Added SQLite3::enableExtendedResultCodes($enable = true), which will make
SQLite3::lastErrorCode() return extended result codes.

– Standard:
. strip_tags() now also accepts an array of allowed tags: Instead of
strip_tags($str, ‘<a><p>’) you can now write strip_tags($str, [‘a’, ‘p’]).

. A new mechanism for custom object serialization has been added, which
uses two new magic methods:

// Returns array containing all the necessary state of the object.
public function __serialize(): array;

// Restores the object state from the given data array.
public function __unserialize(array $data): void;

The new serialization mechanism supersedes the Serializable interface,
which will be deprecated in the future.

RFC: https://wiki.php.net/rfc/custom_object_serialization

. array_merge() and array_merge_recursive() may now be called without any
arguments, in which case they will return an empty array. This is useful
in conjunction with the spread operator, e.g. array_merge(…$arrays).

. proc_open() now accepts an array instead of a string for the command. In
this case the process will be opened directly (without going through a
shell) and PHP will take care of any necessary argument escaping.

proc_open([‘php’, ‘-r’, ‘echo “Hello World\n”;’], $descriptors, $pipes);

. proc_open() now supports “redirect” and “null” descriptors. For example:

// Like 2>&1 on the shell
proc_open($cmd, [1 => [‘pipe’, ‘w’], 2 => [‘redirect’, 1]], $pipes);
// Like 2>/dev/null or 2>nul on the shell
proc_open($cmd, [1 => [‘pipe’, ‘w’], 2 => [‘null’]], $pipes);

. password_hash() has argon2i(d) implementations from ext/sodium when PHP is
built without libargon.

RFC: https://wiki.php.net/rfc/sodium.argon.hash

========================================
3. Changes in SAPI modules
========================================

========================================
4. Deprecated Functionality
========================================

– Core:
. Nesting ternary operators without explicit parentheses is deprecated:

// Code like
$a ? $b : $c ? $d : $e
// should be replaced by (current interpretation)
($a ? $b : $c) ? $d : $e
// or (likely intended interpretation)
$a ? $b : ($c ? $d : $e)

RFC: https://wiki.php.net/rfc/ternary_associativity
. The array and string offset access syntax using curly braces is deprecated.
Use $str[$idx] instead of $str{$idx}.
RFC: https://wiki.php.net/rfc/deprecate_curly_braces_array_access
. The (real) cast is deprecated, use (float) instead.
. Unbinding $this of a non-static method through a combination of
ReflectionMethod::getClosure() and closure rebinding is deprecated. Doing
so is equivalent to calling a non-static method statically, which has been
deprecated since PHP 7.0.
. Unbinding $this of a non-static closure is deprecated.
. Using “parent” inside a class without a parent is deprecated, and will throw
a compile-time error in the future. Currently an error will only be
generated if/when the parent is accessed at run-time.
. The allow_url_include ini directive is deprecated. Enabling it will generate
a deprecation notice at startup.

– COM:
. Importing type libraries with case-insensitive constant registering has been
deprecated.

– Filter:
. FILTER_SANITIZE_MAGIC_QUOTES is deprecated, use FILTER_SANITIZE_ADD_SLASHES
instead.

– Mbstring:
. Passing a non-string pattern to mb_ereg_replace() is deprecated. Currently
non-string patterns are interpreted as ASCII codepoints. In PHP 8 the
pattern will be interpreted as a string instead.
. Passing the encoding as 3rd parameter to mb_strrpos() is deprecated. Instead
pass a 0 offset and encoding as 4th parameter.

– LDAP:
. ldap_control_paged_result_response and ldap_control_paged_result are
deprecated. Pagination controls can be sent along with ldap_search instead.

– Reflection:
. Calls to ReflectionType::__toString() now generate a deprecation notice.
This method has been deprecated in favor of ReflectionNamedType::getName()
in the documentation since PHP 7.1, but did not throw a deprecation notice
for technical reasons.
. The export() methods on all Reflection classes are deprecated. Construct a
Reflection object and convert it to string instead:

// ReflectionClass::export(Foo::class, false) is:
echo new ReflectionClass(Foo::class), “\n”;
// $str = ReflectionClass::export(Foo::class, true) is:
$str = (string) new ReflectionClass(Foo::class);

– Standard:
. Passing invalid characters to ”base_convert()”, ”bindec()”, ”octdec()”
and ”hexdec()” will now generate a deprecation notice. The result will
still be computed as if the invalid characters did not exist. Leading and
trailing whitespace, as well as prefixes of type 0x (depending on base)
continue to be allowed.
. Using array_key_exists() on objects is deprecated. Instead either isset()
or property_exists() should be used.
. The is_real() function is deprecated, use is_float() instead.
. The get_magic_quotes_gpc() and get_magic_quotes_runtime() functions are
deprecated. They always return false.
. The hebrevc() function is deprecated. It can be replaced with
nl2br(hebrev($str)), or preferably the use of Unicode RTL support.
. The convert_cyr_string() function is deprecated. It can be replaced by one
of mb_convert_string(), iconv() or UConverter.
. The money_format() function is deprecated. It can be replaced by the
intl NumberFormatter functionality.
. The ezmlm_hash() function is deprecated.
. The restore_include_path() function is deprecated. It can be replaced by
ini_restore(‘include_path’).
. Passing parameters to implode() in reverse order is deprecated, use
implode($glue, $parts) instead of implode($parts, $glue).

========================================
5. Changed Functions
========================================

– SPL:
. SplFileObject::fputcsv(), ::fgetcsv() and ::setCsvControl() now accept an
empty string as $escape argument, which disables the proprietary PHP
escaping mechanism. SplFileObject::getCsvControl() now may also return an
empty string for the third array element, accordingly.

– Standard:
. fputcsv() and fgetcsv() now accept an empty string as $escape argument,
which disables the proprietary PHP escaping mechanism. The behavior of
str_getcsv() has been adjusted accordingly (formerly, an empty string was
identical to using the default).
. proc_open() on Windows can be passed a “create_process_group” option. It
is required, if the child process is supposed to handle CTRL events.
. password_hash() now accepts nullable string and int as $algo argument.
. password_needs_rehash() now accepts nullable string and int as $algo
argument.

========================================
6. New Functions
========================================

– Core:
. Added get_mangled_object_vars($object) function, which returns the mangled
object properties. It returns the same result as (array) $object, with the
exception that it ignores overloaded array casts, such as used by
ArrayObject.

– GD:
. Added imagecreatefromtga() function, which allows reading images in TGA
format. TGA support is now also indicated by gd_info() and imagetypes().
Note that TGA images are not recognized by imagecreatefromstring() and
getimagesize().

– OpenSSL:
. Added openssl_x509_verify(mixed cert, mixed key) function that verifies the
signature of the certificate using a public key. A wrapper around the
OpenSSL’s X509_verify() function.
See <https://github.com/php/php-src/pull/3624>.

– Pcntl:
. Added bool pcntl_unshare(int flags) function which allows dissociating
parts of the process execution context which are currently being shared with
other processes. Explicitly, it allows you to unshare the mount, IPC, UTS,
network, PID, user and cgroup namespaces.

– SQLite3:
. Added SQLite3Stmt::getSQL() to retrieve the SQL of the statement. If true is
passed as $expanded argument, query parameters will be replaced in the
return value by their currently bound value, if libsqlite ≥ 3.14 is used.
. Added SQLite3::backup() to create database backups via the SQLite3 online
backup API.

– Standard
. bool sapi_windows_set_ctrl_handler(callable handler, [, bool add = true]) –
set or remove a handler function upon receiving a CTRL event. The handler
function is expected to have this signature: “function handler(int $event)”.
. bool sapi_windows_generate_ctrl_event(int type, int pid) – send a CTRL event
to another process.
. array password_algos() – return a complete list of all registered password
hashing algorithms. For more details see the RFC:
https://wiki.php.net/rfc/password_registry

========================================
7. New Classes and Interfaces
========================================

– Reflection:
. A new ReflectionReference class has been added, which allows detecting
references and comparing them for identity. For more details see the RFC:
https://wiki.php.net/rfc/reference_reflection

========================================
8. Removed Extensions and SAPIs
========================================

– Interbase:
. The interbase extension has been moved to PECL. Access to an InterBase
and/or FireBird based database is still available with the PDO_Firebird
extension. For more details see the RFC:
https://wiki.php.net/rfc/deprecate-and-remove-ext-interbase

– Recode:
. The recode extension has been moved to PECL. For character set/encoding
conversion the iconv or mbstring extensions could be used instead.
RFC: https://wiki.php.net/rfc/unbundle_recode

– WDDX:
. The WDDX extension has been deprecated and moved to PECL.
RFC: https://wiki.php.net/rfc/deprecate-and-remove-ext-wddx

========================================
9. Other Changes to Extensions
========================================

– GD:
. The behavior of imagecropauto() in the bundled libgd has been synced with
that of system libgd:
* IMG_CROP_DEFAULT is no longer falling back to IMG_CROP_SIDES
* Threshold-cropping now uses the algorithm of system libgd
. The default $mode parameter of imagecropauto() has been changed to
IMG_CROP_DEFAULT; passing -1 is now deprecated.
. imagescale() now supports aspect ratio preserving scaling to a fixed height
by passing -1 as $new_width.

– Filter:
. The filter extension no longer exposes –with-pcre-dir for Unix builds and
can now reliably be built as shared when using ./configure once more.

– Hash:
. The hash extension cannot be disabled anymore and is always an integral part
of any PHP build, similar to the date extension.

– Intl:
. The Intl extension now requires at least ICU 50.1.
. ResourceBundle now implements Countable.

– Libxml:
. All libxml based extensions now require libxml 2.7.6 or newer.

– Mbstring:
. The oniguruma library is no longer bundled with PHP, instead libonig needs
to be available on the system. Alternatively –disable-mbregex can be used
to disable the mbregex component.

– OPcache:
. The –disable-opcache-file|–enable-opcache-file configure options have been
removed in favor of the opcache.file_cache INI directive.

– PDO:
. It is now possible to escape question marks in SQL queries to avoid them
being interpreted as parameter placeholders. Writing “??” allows sending
a single question mark to the database and e.g. use the PostgreSQL JSON key
exists “?” operator. For more details see the RFC:
https://wiki.php.net/rfc/pdo_escape_placeholders

– Reflection:
. Numeric value of class, property, function and constant modifiers was
changed. Don’t filter methods and properties through
ReflectionClass::getMethods() and ReflectionClass::getProperties(), or test
results of Reflection…::getModifiers(), using hard-coded numeric values.
Use corresponding constants instead (e.g. ReflectionMethod::IS_PUBLIC).

– SimpleXML:
. SimpleXMLElement now implements Countable.

– SQLite3:
. The bundled libsqlite has been removed. To build the SQLite3 extension a
system libsqlite3 ≥ 3.7.4 is now required. To build the PDO_SQLite extension
a system libsqlite3 ≥ 3.5.0 is now required.
. (Un)serialization of SQLite3, SQLite3Stmt and SQLite3Result is now
explicitly forbidden. Formerly, serialization of instances of these classes
was possible, but unserialization yielded unusable objects.
. The @param notation can now also be used to denote SQL query parameters.

– Zip:
. The bundled libzip library has been removed. A system libzip >= 0.11 is now
necessary to build the extension.

========================================
10. New Global Constants
========================================

– Mbstring:
. MB_ONIGURUMA_VERSION specifies the version of the oniguruma library against
which mbregex has been built.

– Socket:
. Added FreeBSD-specific socket options:
. SO_LABEL
. SO_PEERLABEL
. SO_LISTENQLIMIT
. SO_LISTENQLEN
. SO_USER_COOKIE

– Standard:
. PHP_WINDOWS_EVENT_CTRL_C
. PHP_WINDOWS_EVENT_CTRL_BREAK

– Tidy:
. TIDY_TAG_ARTICLE
. TIDY_TAG_ASIDE
. TIDY_TAG_AUDIO
. TIDY_TAG_BDI
. TIDY_TAG_CANVAS
. TIDY_TAG_COMMAND
. TIDY_TAG_DATALIST
. TIDY_TAG_DETAILS
. TIDY_TAG_DIALOG
. TIDY_TAG_FIGCAPTION
. TIDY_TAG_FIGURE
. TIDY_TAG_FOOTER
. TIDY_TAG_HEADER
. TIDY_TAG_HGROUP
. TIDY_TAG_MAIN
. TIDY_TAG_MARK
. TIDY_TAG_MENUITEM
. TIDY_TAG_METER
. TIDY_TAG_NAV
. TIDY_TAG_OUTPUT
. TIDY_TAG_PROGRESS
. TIDY_TAG_SECTION
. TIDY_TAG_SOURCE
. TIDY_TAG_SUMMARY
. TIDY_TAG_TEMPLATE
. TIDY_TAG_TIME
. TIDY_TAG_TRACK
. TIDY_TAG_VIDEO

========================================
11. Changes to INI File Handling
========================================

– zend.exception_ignore_args
. New INI directive to include or exclude arguments from stack traces
generated for exceptions.

========================================
12. Windows Support
========================================

– stat:
. The stat implementation has been refactored.
– An inode number is delivered and is based on the NTFS file index.
– The device number is now based on the volume serial number.

Note that both values are derived from the system and provided as is on 64-bit
systems. On 32-bit systems, these values might overflow the 32-bit integer in
PHP, so they’re fake.

– CTRL+C and CTRL+BREAK on console can be caught by setting a handler function
with sapi_windows_set_ctrl_handler().

– configure now regards additional CFLAGS and LDFLAGS set as environment
variables.

– OPcache now supports an arbitrary amount of separate caches per user via the
the INI directive opcache.cache_id. All processes with the same cache ID and
user share an OPcache instance.

========================================
13. Migration to pkg-config
========================================

A number of extensions have been migrated to exclusively use pkg-config for the
detection of library dependencies. Generally, this means that instead of using
–with-foo-dir=DIR or similar only –with-foo is used. Custom library paths can
be specified either by adding additional directories to PKG_CONFIG_PATH or by
explicitly specifying compilation options through FOO_CFLAGS and FOO_LIBS.

The following extensions and SAPIs are affected:

– Curl:
. –with-curl no longer accepts a directory.

– Enchant:
. –with-enchant no longer accepts a directory.

– FPM:
. –with-fpm-systemd now uses only pkg-config for libsystem checks. The
libsystemd minimum required version is 209.

– GD:
. –with-gd becomes –enable-gd (whether to enable the extension at all) and
–with-external-gd (to opt into using an external libgd, rather than the
bundled one).
. –with-png-dir has been removed. libpng is required.
. –with-zlib-dir has been removed. zlib is required.
. –with-freetype-dir becomes –with-freetype.
. –with-jpeg-dir becomes –with-jpeg.
. –with-webp-dir becomes –with-webp.
. –with-xpm-dir becomes –with-xpm.

– IMAP:
. –with-kerberos no longer accepts a directory.

– Intl:
. –with-icu-dir has been removed. If –enable-intl is passed, then libicu is
always required.

– Ldap:
. –with-ldap-sasl no longer accepts a directory.

– Libxml:
. –with-libxml-dir has been removed.
. –enable-libxml becomes –with-libxml.
. –with-libexpat-dir has been renamed to –with-expat and no longer accepts a
directory.

– LiteSpeed:
. –with-litespeed becomes –enable-litespeed.

– Mbstring:
. –with-onig has been removed. Unless –disable-mbregex has been passed,
libonig is required.

– ODBC:
. –with-iodbc no longer accepts a directory.
. –with-unixODBC without a directory now uses pkg-config (preferred).
Directory is still accepted for old versions without libodbc.pc.

– OpenSSL:
. –with-openssl no longer accepts a directory.
. –with-kerberos no longer accepts a directory.

– PCRE:
. –with-pcre-regex has been removed. Instead –with-external-pcre is provided
to opt into using an external PCRE library, rather than the bundled one.

– PDO_SQLite:
. –with-pdo-sqlite no longer accepts a directory.

– Readline:
. –with-libedit no longer accepts a directory.

– Sodium:
. –with-sodium no longer accepts a directory.

– SQLite3:
. –with-sqlite3 no longer accepts a directory.

– XSL:
. –with-xsl no longer accepts a directory.

– Zip:
. –with-libzip has been removed.
. –enable-zip becomes –with-zip.

========================================
14. Other Changes
========================================

========================================
15. Performance Improvements
========================================

– Core:
. A specialized VM opcode for the array_key_exists() function has been added,
which improves performance of this function if it can be statically
resolved. In namespaced code, this may require writing \array_key_exists()
or explicitly importing the function.

– PCRE:
. When preg_match() in UTF-8 mode (“u” modifier) is repeatedly called on the
same string (but possibly different offsets), it will only be checked for
UTF-8 validity once.

Referrence: PHP.Net

PHP OOP : Siri1 – Apa itu OOP dalam PHP

Tahun 2016 ini jom kita belajar PHP OOP. PakCu akan cuba untuk menterjemahkan konsep OOP dalam PHP sebaik yang mungkin akan lebih mudah untuk dipahami dan dipelajari. Terlebih dahulu, kita semua perlu buangkan tanggapan bahawa mempelajari OOP adalah sangat susah dan kompleks. Setiap benda sekiranya selalu diamalkan akan menjadi mudah akhirnya. Sebagai contoh, cuba tulis nama ada menggunakan tangan kiri (bagi mereka yang lazimnya menggunakan tangan kanan).

Susah bukan? Walaupun nama tersebut biasa kita tulis tapi apabila kita keluar daripada kelaziman kita; bagi kes ini kita menggunakan tangan kiri untuk menulis nama kita, kita akan dapati benda tersebut sukar dilakukan. Begitu juga dengan mempelajari OOP. Pada awalnya akan ada sedikit kesukaran untuk memahami. Namun setelah kita paham dan tahu cara penggunaannya, ia akan memudah dan memahirkan kita.

Secara kita tidak sedar, ada antara kita sebenarnya telah mula menggunakan konsep, struktur dan fungsi asas yang terdapat dalam OOP. Cuma dalam OOP, ia mempunya istilahnya sendiri seperti properties, methods, encaplution, instance dan sebagainya. Insyallah tutorial PHP OOP akan ada beberapa bahagian/siri. Untuk Siri 1 kali ini, PakCu akan lebih kepada pengenalan kepada OOP. Banyak PHP framework yang terdapat dalam pasaran menggunakan konsep OOP dalam struktur framework mereka. Ini disebabkan fungsi OOP telah mengalami perubahan yang besar setelah PHP5 diperkenalkan.


Classes, Properties dan Methods

Class adalah satu blueprint @ template yang menerangkan sesuatu objek. Melalui template ini, berbagai objek yang sama tetapi mempunyai ciri-ciri yang berbeza dapat dihasilkan. Sebagai contoh objek ialah pengguna, apabila kita membina class pengguna ia akan mengandungi maklumat/data/ciri-ciri pengguna. Di dalam OOP, ciri-ciri ini dikenali sebagai properties dan methods.

Untuk menambah/menetapkan data ke dalam sesuatu class, kita menggunakan properties atau lebih dikenali sebagai variables dalam procedural PHP. Contoh properties yang boleh ditetapkan dalam class pengguna adalah id pengguna, email, jantina dan sebagainya.

Method pula adalah kaedah yang lazimnya dipanggil function dalam procedural PHP. Contoh methods yang boleh dicipta dalam class pengguna adalah daftar masuk, daftar keluar, tambah pengguna, hapus pengguna dan sebagainya.

Setelah class dihasilkan, class ini boleh digunakan untuk menetapkan/mencipta pelbagai pengguna lain tetapi berbeza data/maklumat/ciri. Jadi kenapa perlu belajar OOP ini? Dengan adanya ilmu OOP ini kita tidak lagi perlu menulis kod-kod pengaturcaraan secara berulang-ulang untuk sesuatu fungsi. Terdapat istilah DRY (Don’t Repeat Yourself) yang perlu kita amalkan dalam menghasilkan sesuatu aplikasi agar kod kita lebih teratur, mudah dipahami dan yang paling penting senang untuk diselenggara pada masa akan datang sekiranya perlu.

Jumpa lagi di Siri 2 akan datang dengan tajuk Mencipta dan Menggunakan Class.

Kursus PHP & mySQL : Asas

20120524 - RTM-StreamDotMy Sdn Bhd

11879286_10153536823247145_8803056549551592740_oTarikh: 24 – 26 Ogos, 2015
Tempat: IPPTAR, Angkasapuri, Kuala Lumpur
Oleh: Stream.My (Thanks En Azril dan Nazril)

Prinsip MVC untuk Pengaturcara PHP

Apakah itu MVC?

MVC adalah singkatan daripada Model-View-Controller (MVC). Ia adalah satu seni bina perisian (software architecture) atau corak reka bentuk (design pattern) yang digunakan secara meluas dalam pembangunan laman web. Ia biasanya digunakan untuk mencipta aplikasi web atau perisian dengan lebih cekap atau efisyen. Pada topik kali ini, perbincangan MVC adalah dalam skop bahasa pengaturcaraan PHP; satu bahasa pengaturcaraan yang banyak membangunkan framework berkonsepkan MVC, selain daripada ASP.NET, Ruby on Rails dan Zend Framework.

Ketiga-tiga modul utama diterapkan dalam pembangunan web PHP yang mengakibatkan pembangunan aplikasi web berskala dan menarik.

Mengapa anda harus menggunakannya?

Untuk pengaturcara PHP, MVC menawarkan konsep dan idea yang kreatif dan lebih baik berbanding procedural PHP. Pada asasnya, struktur MVC yang menyediakan susunan kod atau fungsi dalam bentuk yang mudah serta dapat menambah fungsi baru dengan lebih efisyen untuk penyesuaian atau penggunaan semula kod agar pembangunan aplikasi menjadi lebih cepat.

MVC membantu pengaturcara PHP menguruskan pembangunan aplikasi web dengan lebih konsisten dan mudah. Melalui MVC juga, anda boleh memisahkan antara logik pengaturcaraan (programming logic) dan kod antara muka (interface code).

Keperluan MVC framework bagi pengaturcara PHP

Dengan menggunakan MVC Framework, pengaturcara PHP dapat membangunkan, menguruskan, menyelenggara dan memastikan prestasi aplikasi web yang dibangunkan dengan lebih mudah, tersusun dan cekap. Terdapat berbagai PHP MVC Framework yang telah dibangunkan seperti Laravel, CakePHP, CodeIgniter, Yii, FuelPHP, Symfony, Kohana, Zend Framework dan sebagainya. Setiap framework mempunyai kelebihan dan kekurangannya tersendiri.

Kebaikan MVC framework

MVC memudahkan anda untuk dalam menaiktaraf dan menyelenggara aplikasi web anda. Selain itu, MVC framework juga mempunyai pengurusan modules yang teratur dan cekap bagi memudahkan pembangunan aplikasi web yang besar. Ia juga memudahkan pengaturcara baru dilantik untuk menyelenggara aplikasi web yang telah dibangunkan menggunakan MVC tersebut. Mereka yang menggunakan struktur dan logik MVC semasa membangunkan aplikasi juga akan mendapati untuk menambah fungsi baru atau menggunakan semula kod-kod yang telah dibuat adalah lebih cepat dan tersusun; terutama bagi mereka yang membangunkan aplikasi web secara berkumpulan. Dengan menggunakan MVC framework, aplikasi web dapat dihasilkan dengan cepat dan seterusnya akan menjimatkan masa pembangunan dan penyelenggaraan.

Struktur fail MVC

MVC framework menawarkan struktur fail dengan paling mudah untuk dipelajari, dipahami dan digunakan seperti View untuk paparan, Model untuk pengurusan pengkalan data Controller sebagai penghubung antara kehendak pengguna (user request) dan paparan yang ingin dilihat. Setiap struktur ini berkait antara satu sama lain. Terdapat juga folder-folder lain di dalam MVC framework yang digunakan sesuai dengan keperluan dan fungsi framework itu sendiri.

Sumber: Codelution.com

 

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

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.