Berikut ini saya akan mencoba untuk mengakses data di tabel Customer yang sudah tersedia di database MySQL dengan menggunakan PHP. Procedure ini akan mem-passing 1 buah parameter yaitu Customer Id nya.

Pertama sya membuat procedure untuk membuat query nya sebagai berikut :

CREATE PROCEDURE `usp_testCustomer3`(
    IN CustId     varchar(18)
)
BEGIN
  select customer_id, customer_name
  from customer
  where customer_id = CustId
  group by customer_id, customer_name;
END

Setelah procedure tercipta, kita coba akses procedure tersebut dengan PHP. Program PHP tersebut saya buat sebagai berikut :

<html>
<body>
<h1>Parsing parameter to a stored procedure</h1>
<pre>
<?php

$mysql = mysql_connect('localhost', 'root', 'triadpass', false, 65536);
mysql_select_db('new_ccrm');

$query = "CALL usp_testCustomer3('01080800051139')";
$result=mysql_query($query) or die(mysql_error());

if ($result)
{
   while ($rows=mysql_fetch_array($result))
   {
          echo trim($rows['customer_id']) . " - " . trim($rows['customer_name']) . "<br>";
   }
   mysql_free_result($result);
}
mysql_close($mysql)

?>
</pre><br>
This demonstration shows a stored procedure to which a parameter has
been passed which is passed in turn into the select query.
</body>
</html>

Setelah itu saya jalankan script PHP tersebut, sehingga outputnya adalah sebagai berikut :

Parsing parameter to a stored procedure

01080800051139 - R. HESTI ENDANG SIREGAR




This demonstration shows a stored procedure to which a parameter has been passed which is passed in turn into the select query.



Nah, ternyata tidak sulit kan membuatnya? Selamat berkreasi dengan procedure-procedure yang lain.

Untuk mengakses data pada database biasanya kita menggunakan query biasa di program, baik itu menggunakan ASP, VB, .Net, PHP atau bahasa pemrograman apapun.

Kali ini saya ingin mencoba untuk mengakses data pada database MySQL dengan memanfaatkan Procedure dan dipanggil menggunakan bahasa pemrograman PHP.

Dengan menggunakan tabel Customer yang sudah tersedia, saya mencoba untuk membuat procedure tanpa parameter untuk menampilkan field Customer Id dan Customer Name.

Pertama saya buat procedurenya dahulu sebagai berikut :

CREATE PROCEDURE `ups_testCustomerNonParam`()
BEGIN
      select * from customer
      order by customer_id
      limit 25;
END

Limit 25 disini maksudnya saya hanya ingin menampilkan sebanyak 25 record saja, karena total keseluruhannya bisa mencapai ratusan ribu reord.

Setelah Procedure ter-create lalu kita buat program PHP untuk memanggil procedure tersebut.

<html>
<body>
<h1>Access Data from a stored procedure</h1>
<pre>
<?php

$mysql = mysql_connect('localhost', 'root', 'triadpass', false, 65536);
mysql_select_db('new_ccrm');

$query = "CALL ups_testCustomerNonParam()";
$result=mysql_query($query) or die(mysql_error());

if ($result)
{
   while ($rows=mysql_fetch_array($result))
   {
          echo trim($rows['customer_id']) . " - " . trim($rows['customer_name']) . "<br>";
   }
   mysql_free_result($result);
}
mysql_close($mysql)

?>
</pre><br>
This demonstration shows a stored procedure to which a parameter has
been passed which is passed in turn into the select query.
</body>
</html>

Nah, setelah itu kita bisa akses program tersebut dan outputnya adalah sebagai berikut :

Access Data from a stored procedure

123 - AMEL
*10120310319990000 - Jeny
0001 - ATIK
0001 - CHINTIA
0001 - ELOK
0001 - EVI
0001 - IREN
0001 - MILA
0001 - NURLAILA
0001 - RATNA
0001 - RODATUL
0001 - SUMIYATI
0001 - TAMY
0001 - VERONIKA
0001 - WINIE
0001 - YANTI
01080800030002 - TJONG NURSANA
01080800030003 - MARIAMAN
01080800030004 - LENA
01080800030005 - HETI
01080800030006 - FITRI
01080800030007 - RISMA TUMORANG
01080800030008 - HETI
01080800030009 - ASIH
01080800030010 - ELI




Mudah bukan caranya? Untuk topik berikutnya, saya akan coba membuat sebuah program PHP singkat untuk mengakses procedure dengan menggunakan parameter.

Pada prinsipnya untuk membuat Stored Procedure dengan 1 atau lebih parameter sama saja. Untuk lebih jelasnya kita coba untuk membuat Stored Procedure nya terlebih dahulu.

CREATE PROCEDURE `usp_testCustomer2`(
   out cu1 varchar(18),
   out cu2 varchar(18)
)
BEGIN
   select min(customer_id) as minimum, max(customer_id) as maksimum
   into cu1, cu2
   from customer;
END

Lalu untuk menjalankan Stored Procedured tersebut sebagai berikut :

set @cust1 = '123';
set @cust2 = 'phonep';
CALL usp_testCustomer2(@cust1, @cust2);
select @cust1, @cust2;

Berikut ini catatan untuk membuat Stored Procedure di MySQL dan memanggil Stored Procedured tersebut.

Pertama kita buat Stored Procedure nya sbb :

CREATE PROCEDURE `usp_testCustomer`(IN custId varchar(18))
BEGIN
  select customer_id, customer_name, count(*) as jumlah
  from customer
  where customer_id = custID
  group by customer_id, customer_name;
END

Setelah itu kita eksekusi Stored Procedure tersebut dengan cara :

set @customer = '01080800051139';
call usp_testCustomer(@customer);

Output yang dihasilkan sbb :

customer_id               customer_name                          jumlah
01080800051139     R. HESTI ENDANG SIREGAR             1

Bila kita ingin parameter yang di-input juga berfungsi sebagai parameter untuk output, caranya adalah sebagai berikut.

Pertama kita buat Stored Procedure nya terlebih dahulu :

CREATE PROCEDURE `usp_testCustomer1`(INOUT custId varchar(18))
BEGIN
  DECLARE custId1 VARCHAR(18) DEFAULT custId;

  select customer_id, customer_name, count(*) as jumlah
  from customer
  where customer_id = custID
  group by customer_id, customer_name;

  set custId = custId1;
END

Setelah itu kita jalankan Stored Procedure tersebut :

set @customer = '01080800051139';
call usp_testCustomer1(@customer);
select @customer;

Output yang dihasilkan  sbb :

customer_id
01080800051139

function convert_number_to_words($number) {
    
    $hyphen      = '-';
    $conjunction = ' and ';
    $separator   = ', ';
    $negative    = 'negative ';
    $decimal     = ' point ';
    $dictionary  = array(
        0                   => 'zero',
        1                   => 'one',
        2                   => 'two',
        3                   => 'three',
        4                   => 'four',
        5                   => 'five',
        6                   => 'six',
        7                   => 'seven',
        8                   => 'eight',
        9                   => 'nine',
        10                  => 'ten',
        11                  => 'eleven',
        12                  => 'twelve',
        13                  => 'thirteen',
        14                  => 'fourteen',
        15                  => 'fifteen',
        16                  => 'sixteen',
        17                  => 'seventeen',
        18                  => 'eighteen',
        19                  => 'nineteen',
        20                  => 'twenty',
        30                  => 'thirty',
        40                  => 'fourty',
        50                  => 'fifty',
        60                  => 'sixty',
        70                  => 'seventy',
        80                  => 'eighty',
        90                  => 'ninety',
        100                 => 'hundred',
        1000                => 'thousand',
        1000000             => 'million',
        1000000000          => 'billion',
        1000000000000       => 'trillion',
        1000000000000000    => 'quadrillion',
        1000000000000000000 => 'quintillion'
    );
    
    if (!is_numeric($number)) {
        return false;
    }
    
    if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
        // overflow
        trigger_error(
            'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
            E_USER_WARNING
        );
        return false;
    }

    if ($number < 0) {
        return $negative . convert_number_to_words(abs($number));
    }
    
    $string = $fraction = null;
    
    if (strpos($number, '.') !== false) {
        list($number, $fraction) = explode('.', $number);
    }
    
    switch (true) {
        case $number < 21:
            $string = $dictionary[$number];
            break;
        case $number < 100:
            $tens   = ((int) ($number / 10)) * 10;
            $units  = $number % 10;
            $string = $dictionary[$tens];
            if ($units) {
                $string .= $hyphen . $dictionary[$units];
            }
            break;
        case $number < 1000:
            $hundreds  = $number / 100;
            $remainder = $number % 100;
            $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
            if ($remainder) {
                $string .= $conjunction . convert_number_to_words($remainder);
            }
            break;
        default:
            $baseUnit = pow(1000, floor(log($number, 1000)));
            $numBaseUnits = (int) ($number / $baseUnit);
            $remainder = $number % $baseUnit;
            $string = convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
            if ($remainder) {
                $string .= $remainder < 100 ? $conjunction : $separator;
                $string .= convert_number_to_words($remainder);
            }
            break;
    }
    
    if (null !== $fraction && is_numeric($fraction)) {
        $string .= $decimal;
        $words = array();
        foreach (str_split((string) $fraction) as $number) {
            $words[] = $dictionary[$number];
        }
        $string .= implode(' ', $words);
    }
    
    return $string;
}
?>

Beberapa fungsi php yang berhubungan dengan url adalah sebagai berikut :

<?php
   echo "Mendapatkan path dari file yang aktif" . "<br>";
   echo $PHP_SELF . "<br><br>";

   $url=parse_url("http://localhost/ford/edit_employee.php?kode_employee=5");

   echo "Mendapatkan url scheme" . "<br>";
   echo $url[scheme] . "<br><br>";

   echo "Mendapatkan url host" . "<br>";
   echo $url[host] . "<br><br>";

   echo "Mendapatkan url path" . "<br>";
   echo $url[path] . "<br><br>";

   echo "Mendapatkan url query" . "<br>";
   echo $url[query] . "<br><br>";

   echo "Mendapatkan nama dari file yang aktif" . "<br>";
   echo basename($PHP_SELF) . "<br><br>";

   echo "Mendapatkan referer" . "<br>";
   echo $HTT

Output yang dihasilkan adalah sbb :

Mendapatkan path dari file yang aktif
/latihan/alamat_url_1.php

Mendapatkan url scheme
http

Mendapatkan url host
localhost

Mendapatkan url path
/ford/edit_employee.php

Mendapatkan url query
kode_employee=5

Mendapatkan nama dari file yang aktif
alamat_url_1.php

Mendapatkan referer

str_replace : menghapus semua karakter spasi

syntax :
str_replace("string_expression1", "string_expression2", "string_expression3")

Contoh :

<?php
   $text = "Jakarta Adalah Ibukota Indonesia";
   $hasil = str_replace(" ","", $text);

   $rawstring = "Your replacement is a pleasure to have!";
   $malestr = str_replace("replacement", "son", $rawstring);

   echo "Sebelum = " . $text . "<br>";
   echo "Sesudah = " . $hasil . "<br><br>";

   echo "Sebelum : Son = " . $rawstring . "<br>";
   echo "Sesudah : Son = " . $malestr . "<br>";
?>

Output :

Sebelum = Jakarta Adalah Ibukota Indonesia
Sesudah = JakartaAdalahIbukotaIndonesia

Sebelum : Son = Your replacement is a pleasure to have!
Sesudah : Son = Your son is a pleasure to have!

-- Data Position utk materna
select cu.customer_id, cu.customer_name, cu.customer_phone, pl.product_id, ch.child_expected_birthday, ca.calling_strike_id
from customer cu, calling ca, product_log pl, children ch
where cu.customer_id = ca.customer_id
          and ca.validation_id = '1'
          and cu.customer_id = pl.customer_id
          and cu.customer_id = ch.customer_id
          and pl.product_id = 'materna'
          and pl.consumed_by = cu.customer_id
          and cu.followup_status = '1'
          and cu.loyalty1_by <> " "
          -- and ca.calling_strike_id <> '12'       
          and ca.calling_result_id = '1'
          and ca.calling_for_id = '3'
          -- and ca.calling_strike_id in ('4','5','10','11','13','14','15')
          and (select ca2.calling_strike_id from calling ca2 where ca2.customer_id = cu.customer_id and ca2.phone_date = (select max(ca1.phone_date) from calling ca1 where ca1.customer_id = cu.customer_id) limit 1) not in ('12', '17')
          and ch.child_expected_birthday <> '0000-00-00'
          and cu.submit_date <= curdate()
          -- and cu.customer_id = '01080800030023'
group by cu.customer_id
order by cu.customer_id
-- limit 100

-- Data Position Anak dgn Produk
-- select aa.umur_anak, aa.product_id, count(aa.umur_anak) as jumlah
-- from
-- (
select ch.child_id, cu.customer_id, ch.child_name, ch.child_birthday,
         -- PERIOD_DIFF(DATE_FORMAT('2010-11-30','%Y%m'),DATE_FORMAT(ch.child_birthday,'%Y%m')) as umur_anak,
         ((datediff(curdate(), ch.child_birthday)) / 30)  as umur_anak,
         -- (case when PERIOD_DIFF(DATE_FORMAT(curdate(),'%Y%m'),DATE_FORMAT(ch.child_birthday,'%Y%m')) between 0 and 6 then 'IF1'
         --         when PERIOD_DIFF(DATE_FORMAT(curdate(),'%Y%m'),DATE_FORMAT(ch.child_birthday,'%Y%m')) between 7 and 12 then 'IF2'
         --         when PERIOD_DIFF(DATE_FORMAT(curdate(),'%Y%m'),DATE_FORMAT(ch.child_birthday,'%Y%m')) between 13 and 36 then 'ESS3'
         -- end) as product_id,
         -- (case when ((datediff(curdate(), ch.child_birthday)) / 30)  >= 0 and ((datediff(curdate(), ch.child_birthday)) / 30)  <= 6  then 'IF1'
         --          when ((datediff(curdate(), ch.child_birthday)) / 30)  > 6   and ((datediff(curdate(), ch.child_birthday)) / 30)  <= 12 then 'IF2'
         --          when ((datediff(curdate(), ch.child_birthday)) / 30)  > 12 and ((datediff(curdate(), ch.child_birthday)) / 30)  <= 36 then 'ESS3'
         --          when ((datediff(curdate(), ch.child_birthday)) / 30)  > 36 then 'ESS4'
         -- end) as product_id,
         pl.product_id,
         cl.calling_result_id,
         cu.customer_address, cu.customer_phone, cu.customer_phone_2
from children ch
inner join  customer cu  on ch.customer_id = cu.customer_id
inner join  calling cl on cl.customer_id = cu.customer_id
inner join product_log pl on pl.customer_id = cu.customer_id
where ((ch.child_birthday >= (date_sub(curdate(), interval 37 month)))
and (ch.child_birthday <= (date_sub(curdate(), interval 0 month))))
and (ch.child_birthday<> '0000-00-00' or ch.child_birthday like '0001-00-00')
and cl.validation_id='1'
and cu.followup_status = '1'
and cl.calling_result_id = '1'
and pl.consumed_by = ch.child_id
and (select ca2.calling_strike_id from calling ca2 where ca2.customer_id = cu.customer_id and ca2.phone_date = (select max(ca1.phone_date) from calling ca1 where ca1.customer_id = cu.customer_id) limit 1) not in ('6', '12', '16')
and pl.product_id in ('if1', 'if2', 'ess3', 'ess4')
group by ch.child_id
order by ch.child_id, ch.child_birthday
-- limit 60000,60000
-- ) aa
-- group by aa.umur_anak, aa.product_id
-- order by aa.umur_anak

strcasecmp : membandingkan 2 string yang tidak case sensitive

syntax :
strcasecmp (string $str1, string $str2)

akan menghasilkan < 0 jika str1 < str2
                                     > 0 jika str1 > str2
                                     = 0 jika data sama

Contoh :

<?php
$kata1 = "Jakarta";
$kata2 = "jaKarta";

if (strcasecmp($kata1,$kata2) == 0)
{
    echo "Kata antara " . $kata1 . " dan " . $kata2 . " sama ...";
}
else
{
    echo "Kata tidak sama ...";
}
?>

 

Output yang dihasilkan adalah sbb :

Kata antara Jakarta dan jaKarta sama ...