Tuesday, December 2, 2014

การเขียน PHP ติดต่อกับ DBF (PHP Connect to DBASE or DBF FILE)


<?php
$connection_string = 'DRIVER={Microsoft dBase Driver (*.dbf)};datasource=C:\AppServ\www\subject.dbf;';
$user = '';
$pass = '';
 $odbc = odbc_connect ($connection_string, '', '') or die('Could Not Connect to ODBC Database!');
$strsql= 'SELECT * FROM C:\AppServ\www\subject.dbf';
$query = odbc_exec($odbc, $strsql) or die (odbc_errormsg());
while($row = odbc_fetch_object($query)){
echo $row->SUBNAME."<br>";
}
?>

Monday, November 24, 2014

function การใช้งาน Dbase ดังนี้ 
  • dbase_add_record เพิ่มข้อมูลเข้าฐานข้อมูล
  • dbase_close ปิดฐานข้อมูล
  • dbase_create สร้างฐานข้อมูล
  • dbase_delete_record ลบแถวข้อมูลออกจากฐานข้อมูล
  • dbase_get_header_info อ่านข้อมูลรายละเอียดของฐานข้อมูล
  • dbase_get_record_with_names อ่านแถวข้อมูลจากฐานข้อมูล ออกมาเป็นอาร์เรย์เป็นชื่อคีย์
  • dbase_get_record อ่านแถวข้อมูลจากฐานข้อมูล ออกมาเป็นอาร์เรย์เป็นชื่ออินเดก
  • dbase_numfields อ่านจำนวนฟิลด์ของไฟล์ฐานข้อมูล
  • dbase_numrecords อ่านจำนวนแถวข้อมูลทั้งหมดในฐานข้อมูล
  • dbase_open เปิดฐานข้อมูล
  • dbase_pack แพคฐานข้อมูล
  • dbase_replace_record แทนที่แถวของฐานข้อมูล

ตัวอย่างการใช้งาน
<?php
$db = dbase_open('C:/AppServ/www/test.dbf', 0);
if(
$db){
$record_numbers = dbase_numrecords($db);
for(
$i = 1; $i <= $record_numbers; $i++){
$row = dbase_get_record_with_names($db, $i);
echo
$row['name']. "<br/>";
}
}
?>

Friday, October 3, 2014

อัตราแลกเปลี่ยนเงินไทยกับดอลล่าร์โดย JSON (Curency Exchange By JSON)

<?
$url="http://rate-exchange.appspot.com/currency?from=USD&to=THB&q=1";
$contents = file_get_contents($url);
$jsonObj = json_decode($contents);
echo "1 ".$jsonObj->{'from'};
echo " is ".$jsonObj->{'rate'};
echo " ".$jsonObj->{'to'};
?>

ฟังก์ชั่นแสดงวันที่โดยใช้ PHP (PHP Function Get Date Time)

<?
function getdatetime(){
$datetime=date("Y-m-d H:i:s");
return $datetime;
}
echo getdatetime();
?>

สร้างกรอบรูปโดยใช้ HTML (Image Border By HTML)

<img src="image.png" width="100" height="10" border="0" alt="" style="border: 1px solid #ccc; padding: 5px;">

เปลี่ยนรูปให้โปร่งใสเมื่อวางเมาส์บนรูป (Opacity Image on Mouseover)

<img src="yourimage.png" width="100" height="10" border="0" alt="" style="opacity:0.5;filter:alpha(opacity=50)" onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100" onmouseout="this.style.opacity=0.5;this.filters.alpha.opacity=50">

ฟังก์ชั่น หาค่าไอพี โดยใช้ PHP (Get IP Address By PHP)

<?
function getIP(){
if ($_SERVER['HTTP_CLIENT_IP']) { 
$IP = $_SERVER['HTTP_CLIENT_IP'];
} elseif (ereg("[0-9]",$_SERVER["HTTP_X_FORWARDED_FOR"] )) { 
$IP = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else { 
$IP = $_SERVER["REMOTE_ADDR"];
}
return $IP;
}

echo "Your IP is".getIP();
?>

การลบวันที่สองวันโดยใช้ PHP DateDiff (Date Difference By PHP)

<?
function DateDiff($strDate1,$strDate2)
{
return (strtotime($strDate2) - strtotime($strDate1))/ ( 60 * 60 * 24 ); // 1 day = 60*60*24
}

echo DateDiff("2014-10-01","2014-10-05");
?>


การใช้ CSS สร้างตารางโค้ง (CSS CURV Table)

#td{
color: black;
border: 1px solid #FEDDFE;
-webkit-border-radius: 1px;
}

ฟังก์ชั่น PHP ตรวจสอบคำภาษาไทย(PHP Check Thai Word)

<?
function checkthai($word){
return preg_replace('/[^ก-๙]/u','',$word);
}
$checkthaiword=trim(checkthai('บันทึกข้อความ!!'));

if($checkthaiword != ""){ echo "มีภาษาไทย"; }

?>

คำสั่งแทนที่ Mysql (MySQL Replace Word)

UPDATE TableName SET FieldName = REPLACE( FieldName ,'search word','replace word')

สลับสีตาราง bootstrap โดยใช้ css (swith bootstrap table color by css)

<style>
.table tbody tr:hover td, .table tbody tr:hover th {
background-color: #111111;
}
</style>

แก้ปัญหา niceedit วางจาก word (config Copy&Past Nice Edit form Microsoft Word)


var nicEditorInstance = bkClass.extend({
isSelected : false,

construct : function(e,options,nicEditor) {
this.ne = nicEditor;
this.elm = this.e = e;
this.options = options || {};

newX = parseInt(e.getStyle('width')) || e.clientWidth;
newY = parseInt(e.getStyle('height')) || e.clientHeight;
this.initialHeight = newY-8;

var isTextarea = (e.nodeName.toLowerCase() == "textarea");
if(isTextarea || this.options.hasPanel) {
var ie7s = (bkLib.isMSIE && !((typeof document.body.style.maxHeight != "undefined") && document.compatMode == "CSS1Compat"))
var s = {width: newX+'px', border : '2px solid #F1F1F1', borderTop : 0, overflowY : 'auto', overflowX: 'hidden' };
s[(ie7s) ? 'height' : 'maxHeight'] = (this.ne.options.maxHeight) ? this.ne.options.maxHeight+'px' : null;
this.editorContain = new bkElement('DIV').setStyle(s).appendBefore(e);

/* CLEAN WORD PASTE MOD */
//var editorElm = new bkElement('DIV').setAttributes({id : e.id}).setStyle({width : (newX-8)+'px', margin: '4px', minHeight : newY+'px'}).addClass('main').appendTo(this.editorContain);
var editorElm = new bkElement('DIV').setStyle({width : (newX-8)+'px', margin: '4px', minHeight : newY+'px'}).addClass('main').appendTo(this.editorContain);

e.setStyle({display : 'none'});
editorElm.innerHTML = e.innerHTML;
if(isTextarea) {
editorElm.setContent(e.value);
this.copyElm = e;
var f = e.parentTag('FORM');
if(f) { bkLib.addEvent( f, 'submit', this.saveContent.closure(this)); }
}
editorElm.setStyle((ie7s) ? {height : newY+'px'} : {overflow: 'hidden'});
this.elm = editorElm;

}
this.ne.addEvent('blur',this.blur.closure(this));

this.init();
this.blur();
},

init : function() {
this.elm.setAttribute('contentEditable','true');
if(this.getContent() == "") {
this.setContent('<br />');
}
this.instanceDoc = document.defaultView;
this.elm.addEvent('mousedown',this.selected.closureListener(this)).addEvent('keypress',this.keyDown.closureListener(this)).addEvent('focus',this.selected.closure(this)).addEvent('blur',this.blur.closure(this)).addEvent('keyup',this.selected.closure(this));
this.ne.fireEvent('add',this);

/* CLEAN WORD PASTE MOD */
this.elm.addEvent('paste',this.initPasteClean.closureListener(this));
},

initPasteClean : function() {
this.pasteCache = this.getElm().innerHTML;
setTimeout(this.pasteClean.closure(this),100);
},

/* CLEAN WORD PASTE MOD : pasteClean method added for clean word paste */
pasteClean : function() {
var matchedHead = "";
var matchedTail = "";
var newContent = this.getElm().innerHTML;
this.ne.fireEvent("get",this);
var newContentStart = 0;
var newContentFinish = 0;
var newSnippet = "";
var tempNode = document.createElement("div");

/* Find start of both strings that matches */

for (newContentStart = 0; newContent.charAt(newContentStart) == this.pasteCache.charAt(newContentStart); newContentStart++)
{
matchedHead += this.pasteCache.charAt(newContentStart);
}

/* If newContentStart is inside a HTML tag, move to opening brace of tag */
for (var i = newContentStart; i >= 0; i--)
{
if (this.pasteCache.charAt(i) == "<")
{
newContentStart = i;
matchedHead = this.pasteCache.substring(0, newContentStart);

break;
}
else if(this.pasteCache.charAt(i) == ">")
{
break;
}
}

newContent = this.reverse(newContent);
this.pasteCache = this.reverse(this.pasteCache);

/* Find end of both strings that matches */
for (newContentFinish = 0; newContent.charAt(newContentFinish) == this.pasteCache.charAt(newContentFinish); newContentFinish++)
{
matchedTail += this.pasteCache.charAt(newContentFinish);
}

/* If newContentFinish is inside a HTML tag, move to closing brace of tag */
for (var i = newContentFinish; i >= 0; i--)
{
if (this.pasteCache.charAt(i) == ">")
{
newContentFinish = i;
matchedTail = this.pasteCache.substring(0, newContentFinish);

break;
}
else if(this.pasteCache.charAt(i) == "<")
{
break;
}
}

matchedTail = this.reverse(matchedTail);

/* If there's no difference in pasted content */
if (newContentStart == newContent.length - newContentFinish)
{
return false;
}

newContent = this.reverse(newContent);
newSnippet = newContent.substring(newContentStart, newContent.length - newContentFinish);
newSnippet = this.validTags(newSnippet);

/* Replace opening bold tags with strong */
newSnippet = newSnippet.replace(/<b(\s+|>)/g, "<strong$1");
/* Replace closing bold tags with closing strong */
newSnippet = newSnippet.replace(/<\/b(\s+|>)/g, "</strong$1");

/* Replace italic tags with em */
newSnippet = newSnippet.replace(/<i(\s+|>)/g, "<em$1");
/* Replace closing italic tags with closing em */
newSnippet = newSnippet.replace(/<\/i(\s+|>)/g, "</em$1");

/* strip out comments -cgCraft */
newSnippet = newSnippet.replace(/<!(?:--[\s\S]*?--\s*)?>\s*/g, "");

/* strip out &nbsp; -cgCraft */
newSnippet = newSnippet.replace(/&nbsp;/gi, " ");
/* strip out extra spaces -cgCraft */
newSnippet = newSnippet.replace(/ <\//gi, "</");

while (newSnippet.indexOf(" ") != -1) {
var anArray = newSnippet.split(" ")
newSnippet = anArray.join(" ")
}

/* strip &nbsp; -cgCraft */
newSnippet = newSnippet.replace(/^\s*|\s*$/g, "");

/* Strip out unaccepted attributes */

newSnippet = newSnippet.replace(/<[^>]*>/g, function(match)
{
match = match.replace(/ ([^=]+)="[^"]*"/g, function(match2, attributeName)
{
if (attributeName == "alt" || attributeName == "href" || attributeName == "src" || attributeName == "title")
{
return match2;
}

return "";
});

return match;
}
);

/* Final cleanout for MS Word cruft */
newSnippet = newSnippet.replace(/<\?xml[^>]*>/g, "");
newSnippet = newSnippet.replace(/<[^ >]+:[^>]*>/g, "");
newSnippet = newSnippet.replace(/<\/[^ >]+:[^>]*>/g, "");

/* remove undwanted tags */
newSnippet = newSnippet.replace(/<(div|span|style|meta|link){1}.*?>/gi,'');

this.content = matchedHead + newSnippet + matchedTail;
this.ne.fireEvent("set",this);
this.elm.innerHTML = this.content;
},

reverse : function(sentString) {
var theString = "";
for (var i = sentString.length - 1; i >= 0; i--) {
theString += sentString.charAt(i);
}
return theString;
},

/* CLEAN WORD PASTE MOD : validTags method added for clean word paste */
validTags : function(snippet) {
var theString = snippet;

/* Replace uppercase element names with lowercase */
theString = theString.replace(/<[^> ]*/g, function(match){return match.toLowerCase();});

/* Replace uppercase attribute names with lowercase */
theString = theString.replace(/<[^>]*>/g, function(match) {
match = match.replace(/ [^=]+=/g, function(match2){return match2.toLowerCase();});
return match;
});

/* Put quotes around unquoted attributes */
theString = theString.replace(/<[^>]*>/g, function(match) {
match = match.replace(/( [^=]+=)([^"][^ >]*)/g, "$1\"$2\"");
return match;
});

return theString;
},

remove : function() {
this.saveContent();
if(this.copyElm || this.options.hasPanel) {
this.editorContain.remove();
this.e.setStyle({'display' : 'block'});
this.ne.removePanel();
}
this.disable();
this.ne.fireEvent('remove',this);
},

disable : function() {
this.elm.setAttribute('contentEditable','false');
},

getSel : function() {
return (window.getSelection) ? window.getSelection() : document.selection;
},

getRng : function() {
var s = this.getSel();
if(!s) { return null; }
return (s.rangeCount > 0) ? s.getRangeAt(0) : s.createRange();
},

selRng : function(rng,s) {
if(window.getSelection) {
s.removeAllRanges();
s.addRange(rng);
} else {
rng.select();
}
},

selElm : function() {
var r = this.getRng();
if(r.startContainer) {
var contain = r.startContainer;
if(r.cloneContents().childNodes.length == 1) {
for(var i=0;i<contain.childNodes.length;i++) {
var rng = contain.childNodes[i].ownerDocument.createRange();
rng.selectNode(contain.childNodes[i]);
if(r.compareBoundaryPoints(Range.START_TO_START,rng) != 1 &&
r.compareBoundaryPoints(Range.END_TO_END,rng) != -1) {
return $BK(contain.childNodes[i]);
}
}
}
return $BK(contain);
} else {
return $BK((this.getSel().type == "Control") ? r.item(0) : r.parentElement());
}
},

saveRng : function() {
this.savedRange = this.getRng();
this.savedSel = this.getSel();
},

restoreRng : function() {
if(this.savedRange) {
this.selRng(this.savedRange,this.savedSel);
}
},

keyDown : function(e,t) {
if(e.ctrlKey) {
this.ne.fireEvent('key',this,e);
}
},

selected : function(e,t) {
if(!t) {t = this.selElm()}
if(!e.ctrlKey) {
var selInstance = this.ne.selectedInstance;
if(selInstance != this) {
if(selInstance) {
this.ne.fireEvent('blur',selInstance,t);
}
this.ne.selectedInstance = this;
this.ne.fireEvent('focus',selInstance,t);
}
this.ne.fireEvent('selected',selInstance,t);
this.isFocused = true;
this.elm.addClass('selected');
}
return false;
},

blur : function() {
this.isFocused = false;
this.elm.removeClass('selected');
},

saveContent : function() {
if(this.copyElm || this.options.hasPanel) {
this.ne.fireEvent('save',this);
(this.copyElm) ? this.copyElm.value = this.getContent() : this.e.innerHTML = this.getContent();
}
},

getElm : function() {
return this.elm;
},

getContent : function() {
this.content = this.getElm().innerHTML;
this.ne.fireEvent('get',this);
return this.content;
},

setContent : function(e) {
this.content = e;
this.ne.fireEvent('set',this);
this.elm.innerHTML = this.content;
},

nicCommand : function(cmd,args) {
document.execCommand(cmd,false,args);
}
});

SPHInX

Seamless Provincial Healthcare Innovation & Excellence: SPHInX

Thursday, October 2, 2014

รหัสการพยากรณ์อากาศ สำหรับ Yahoo ของประเทศไทย (YAHOO WEATHER CODE THAILAND)

WEATHER CODE THAILAND

THXX0001, Ban Phai
THXX0002, Bangkok
THXX0003, Chiang Mai
THXX0004, Chon Buri
THXX0005, Chum Phae
THXX0006, Hua Hin
THXX0007, Khok Kloi
THXX0008, Khon Kaen
THXX0009, Lampang
THXX0010, Lamphun
THXX0011, Mae Rim
THXX0012, Maha Sarakham
THXX0013, Nakhon Pathom
THXX0014, Nakhon Ratchasima
THXX0015, Pattaya
THXX0016, Phetchaburi
THXX0017, Phra Nakhon Si Ayutthaya
THXX0018, Phuket
THXX0019, Roi Et
THXX0020, Sakhon Nakhon
THXX0021, Samut Prakan
THXX0022, Samut Sakhon
THXX0023, Saraphi
THXX0024, Thai Muang
THXX0025, Thalang
THXX0026, Udon Thani
THXX0027, Mae Hong Son
THXX0028, Phayao
THXX0029, Mae Sariang
THXX0031, Nan
THXX0032, Nong Khai
THXX0033, Loei
THXX0034, Mae Sot
THXX0035, Phitsanulok
THXX0036, Kam Paeng Phet
THXX0037, Mukdahan
THXX0038, Chaiyaphum
THXX0039, Ubon Ratchathani
THXX0040, Thong Pha Phum
THXX0041, Suphan Buri
THXX0042, Prachin Buri
THXX0043, Kanchanaburi
THXX0044, Chanthaburi
THXX0045, Prachuap Khirikhan
THXX0046, Ko Samui
THXX0047, Surat Thani
THXX0048, Nakhon Si Thammarat
THXX0049, Songkhla
THXX0050, Hat Yai
THXX0051, Narathiwat
THXX0053, Lopburi
THXX0054, Nonthaburi

ฟังก์ชั่น PHP ในการสุ่มรหัสผ่าน (Random Password PHP)

Random Password PHP
<? function Randpwd() {
 $length = 14;
 $letters = '1234567890qwertyuiopasdfghjklzxcvbnm';
 $s = '';
 $lettersLength = strlen($letters)-1;

 for($i = 0 ; $i < $length ; $i++)
 {
 $s .= $letters[rand(0,$lettersLength)];
 }
 return $s;
 }

echo Randpwd();
?>

ฟังก์ชั่น PHP หลักการสุ่มสีเพื่อใช้กับ Amcharts (Random Color For Amcharts)

(Random Color For Amcharts)
<? function RandCol() {
 $length = 6;
 $letters = '1234567890ABCDEF';
 $s = '';
 $lettersLength = strlen($letters)-1;

 for($i = 0 ; $i < $length ; $i++)
 {
 $s .= $letters[rand(0,$lettersLength)];
 }
 return $s;
 }
?>
<? echo RandCol();?>

โค้ดเพื่อใช้งานกราฟ Amcharts กับ PHP,MySQL (Amcharts PHP MySQL)

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>amCharts examples</title>
        <link rel="stylesheet" href="style.css" type="text/css">
        <script src="amcharts/amcharts.js" type="text/javascript"></script>
        <script src="amcharts/serial.js" type="text/javascript"></script>

        <script type="text/javascript">
            var chart;

            var chartData = [
<?
$sql=mysql_query("select count(program) as total,program from jobs group by program having count(program) > 5;");
$num=mysql_num_rows($sql);
$n=0;
while($row=mysql_fetch_object($sql)){
$n=$n+1;
?>
                {
                    "program": "<?=$row->program;?>",
                    "จำนวน": <?=$row->total;?>,
                    "color": "#FEDFEE"
                }<? if($n<$num){?>,<?}else{?><?}?>
<?}?>

            ];


            AmCharts.ready(function () {
                // SERIAL CHART
                chart = new AmCharts.AmSerialChart();
                chart.dataProvider = chartData;
                chart.categoryField = "program";
                // the following two lines makes chart 3D
                chart.depth3D = 20;
                chart.angle = 30;

                // AXES
                // category
                var categoryAxis = chart.categoryAxis;
                categoryAxis.labelRotation = 90;
                categoryAxis.dashLength = 5;
                categoryAxis.gridPosition = "start";

                // value
                var valueAxis = new AmCharts.ValueAxis();
                valueAxis.title = "จำนวน";
                valueAxis.dashLength = 5;
                chart.addValueAxis(valueAxis);

                // GRAPH
                var graph = new AmCharts.AmGraph();
                graph.valueField = "จำนวน";
                graph.colorField = "color";
                graph.balloonText = "<span style='font-size:14px'>[[category]]: <b>[[value]]</b></span>";
                graph.type = "column";
                graph.lineAlpha = 0;
                graph.fillAlphas = 1;
                chart.addGraph(graph);

                // CURSOR
                var chartCursor = new AmCharts.ChartCursor();
                chartCursor.cursorAlpha = 0;
                chartCursor.zoomable = false;
                chartCursor.categoryBalloonEnabled = false;
                chart.addChartCursor(chartCursor);

                chart.creditsPosition = "top-right";


                // WRITE
                chart.write("chartdiv");
            });
        </script>
    </head>

    <body>
<div class="panel panel-info" style="width:100%">
 <div class="panel-heading">โปรแกรม</div>
 <div class="panel-body">
        <div id="chartdiv" style="width: 100%; height: 400px;"></div>
</div>
</div>
    </body>

</html>

การสร้าง weather code เพื่อติดที่เว็บไซต์ (PHP Create Weather on Web By Yahoo)

โค้ด weather code เพื่อแสดงอุณหภูมิที่เว็บไซต์

<?php
$result = file_get_contents('http://weather.yahooapis.com/forecastrss?p=THXX0039&u=c');
$xml = simplexml_load_string($result);

//echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');

$xml->registerXPathNamespace('yweather', 'http://xml.weather.yahoo.com/ns/rss/1.0');
$location = $xml->channel->xpath('yweather:location');

if(!empty($location)){
foreach($xml->channel->item as $item){
$current = $item->xpath('yweather:condition');
$forecast = $item->xpath('yweather:forecast');
$current = $current[0];
$output = <<<END
<p>
<span style="font-size:30pt;">{$current['temp']}&deg;C</span>
<br/>
<img src="http://s.imwx.com/v.20131006.215409/img/wxicon/100/%7B$current['code']%7D.png" style="vertical-align: middle;"/><br>
{$current['text']}
</p>

END;
}
}else{
$output = '<h1>No results found, please try a different zip code.</h1>';
}
?>

การเขียนโปรแกรมภาษา swift โดยมาสเตอร์อึ่ง

การเขียนโปรแกรมภาษา swift

การ Limit คำสั่ง SQL SERVER (Limit MsSQL)

ถ้าใน MySQL จะใช้คำสั่ง Limit แต่ถ้าใน MsSQL
การ Limit คำสั่ง SQL SERVER จะใช้รูปแบบตามนี้ครับ

SELECT * FROM ( SELECT *, ROW_NUMBER() OVER 
(ORDER BY UserCode) as row FROM profile) a 
WHERE row > '100' and row <='200'

จะเห็นว่าไม่ยากเลยใช่ไหมครับ