SQLCommand.php
<?php
if (! defined ( "S_CHARACTOR" ))
define ( "S_CHARACTOR", 1001 );
if (! defined ( "S_NUMERIC" ))
define ( "S_NUMERIC", 1002 );
if (! defined ( "S_BLOB" ))
define ( "S_BLOB", 1003 );
if (! defined ( "S_DATETIME" ))
define ( "S_DATETIME", 1004 );
/** @package Databases */
class SQLCommand {
/**
* array list variable parameter
*
* @var array
*/
private $a_assign_var;
/**
* array list value for list parameter
*
* @var array
*/
private $a_assign_value;
/**
* Source sql command before parsing sql command.
*
* @var string
*/
private $s_sql_source;
/**
* Constructor
* $o_ new SQLCommand("select * from tbl1 where col1 = :c_1");
* $o_->setValue("c_1","name");
* print $o_->parseSQL();
*
* @param string $s_sql_source
*/
function __construct($s_sql_source = '') {
$this->s_sql_source = $s_sql_source;
}
/**
* Assgin value on mark point from sql command.
*
* @param string $s_marker
* @param string $s_values
*/
public function setValue($s_marker, $s_values, $s_col_type = S_CHARACTOR) {
$this->a_assign_var [] = "/:" . $s_marker . "/";
if ($s_col_type === S_CHARACTOR) {
$this->a_assign_value [] = "'" . $s_values . "'";
} else if ($s_col_type === S_DATETIME) {
$this->a_assign_value [] = "'" . $s_values . "'";
} else {
$this->a_assign_value [] = $s_values;
}
}
/**
* Set source Sql command.
*
* @param string $s_sql
*/
public function setSql($s_sql = '') {
$this->s_sql_source = $s_sql;
}
/**
* Get source Sql command.
*
* @return string
*/
public function getSql() {
return $this->s_sql_source;
}
/**
* Return parsing sql command.
*
* @return string
*/
public function parseSQL() {
return preg_replace ( $this->a_assign_var, $this->a_assign_value, $this->s_sql_source );
}
}
?>[/code]
การใช้งาน
[code]UseSQLCommand.php
<?php
include_once "SQLCommand.php";
$s_sql = "INSERT INTO tbl_teacher ( title_name_id, name, middle_name, surname, email, faculty, created_at, updated_at) VALUES( :title_name_id, :name, :middle_name, :surname, :email, :faculty, :created_at, :updated_at);";
print "ก่อน กำหนดค่า<br>";
print $s_sql."<br>";
$o_sql_cmd = new SQLCommand ( $s_sql );
$o_sql_cmd->setValue ( 'title_name_id', 1, S_NUMERIC );
$o_sql_cmd->setValue ( 'name', "ชื่อ" , S_CHARACTOR );
$o_sql_cmd->setValue ( 'middle_name', "ชื่อกลาง", S_CHARACTOR );
$o_sql_cmd->setValue ( 'surname',"สกุล", S_CHARACTOR );
$o_sql_cmd->setValue ( 'faculty',"วิทยาศาสตร์" , S_CHARACTOR );
$o_sql_cmd->setValue ( 'email', "[email protected]" , S_CHARACTOR );
$o_sql_cmd->setValue ( 'created_at', date ( "Y-m-d H:i:s" ), S_DATETIME );
$o_sql_cmd->setValue ( 'updated_at', date ( "Y-m-d H:i:s" ), S_DATETIME );
print "หลัง กำหนดค่า<br>";
print $o_sql_cmd->parseSQL () ; // จะคืนค่ากลับมาเป็น คำสั่ง Sql ที่สามารถนำไปส่งฐานข้อมูลประมวลผลได้เลย แต่สำหรับตรงนี้ผมให้มันแสดงออกทางหน้าเว็บ
?>