トップ «前の日(12-08) 最新 次の日(12-10)» 追記

Masa's blog

検索キーワード:

2016年12月09日 PHP memo

_ Hello.php

<?php
	echo "Hello World!";
?>

_ args(command line)

#! /usr/bin/php
#
# ./args.php aaa bbb ccc
#
<?php
        echo "$argc\n";			# 4

        for ($i = 0; $i < $argc; $i++){
                 echo $argv[$i] . "\n";	# show $argv[0] to $argv[3] and $argv[0] is "./args.php"
        }

        foreach ($argv as $arg){
                echo $arg . "\n";
        }
?>

_ args(cgi)

<?php
	if ($_SERVER["REQUEST_METHOD"] == "POST"){
 		$id = $_POST['id'];
 	}else{
 		$id = $_GET['id'];
 	}
 	print "id is " . htmlspecialchars($id) . "<br>";
?>

_ stdio

<?php
 	print "Hello";				# without CRLF
 	print "Hello\n";			# with CRLF
 	printf("%s\n","Hello");			# with CRLF
 	fprintf(STDOUT,"%s\n","Hello");		# with CRLF

 	fputs(STDOUT, "Input: ");
 	$input = fgets(STDIN);

 	print "[$input]\n";		# with CRLF
 	$output = trim($input);		# suppress top space and bottom space
 	print "[$output]\n";
 	$output = ltrim($input);	# suppress top space
 	print "[$output]\n";
 	$output = rtrim($input);	# suppress bottom space
 	print "[$output]\n";
?>

_ variable

<?php
 	$str1 = "string";
 	$str2 = "This is ${str1}\n";				# "This is string"
 	$str3 = 'This is ${str1}\n';				# 'This is ${str1}\n'
 	$str5 = substr("This is string", 5, 2);			# "is"
 	$str6 = substr("これはUTF8文字列です", 9, 12);		# "UTF8"
 	$str7 = mb_substr("これはUTF8文字列です", 3, 7, "UTF-8");	# "UTF8文字列"
?>

_ list

<?php
 	$array3 = [ "data1", "data2", "data3" ];
 	print $array3[1] . "\n";			# "data2"

 	$array4[0] = "data1";
 	$array4[2] = "data3";
 	print count($array4) . "\n";			# 2

 	$array5 = [ "data1", "data2", "data3" ];
 	foreach ($array5 as $value){
 		print $value . "\n";
 	}
?>

_ hash

<?php
 	$array1 = [ "key1" => "data1", "key2" => "data2", "key3" => "data3" ];
 	print $array1["key2"] . "\n";			# "data2"

 	$array2["key1"] = "data1";
 	$array2["key2"] = "data2";
 	$array2["key3"] = "data3";
 	print $array2["key2"] . "\n";			# "data2"

 	$array6 = [ "key1" => "data1", "key2" => "data2", "key3" => "data3" ];
 	foreach ($array6 as $key => $value){
 		print $key . " => " . $value . "\n";
 	}
?>

_ operator

<?php
 	$wk = "abc" . "def";	# "abcdef"
 	$wk = 10 + 20;		# 30
 	$wk = 10 - 20;		# -10
 	$wk = 10 * 20;		# 200
 	$wk = 10 / 20;		# 0.5
 	$wk = 10.0 / 20;	# 0.5
 	$wk = pow(3, 2);	# 9
 	$wk = 7 % 5;		# 2
?>

_ if

<?php
 	$wk1 = 10;
 	$wk2 = 20;
 	$wk3 = 30;
 	$wk4 = 40;

 	if ($wk1 == $wk2){
 		print "cond1\n";
 	}elseif ($wk1 > $wk2){
 		print "cond2\n";
 	}else{
 		print "cond3\n";	# true
 	}

 	if ($wk1 != $wk2){
 		print "cond1\n";	# true
 	}else{
 		print "cond2\n";
 	}

 	if ($wk1 < $wk2 &&
 	    $wk3 < $wk4){
 		print "cond1\n";	# true
 	}else{
 		print "cond2\n";
 	}
?>

_ while

<?php
 	while ($rec = fgets(STDIN)){
 		$rec = trim($rec);
 		print $rec . "\n";
 	}
?>

_ for, foreach

<?php
 	for ($i = 0; $i < 5; $i++){
 		print $i . "\n";
 	}

 	$list = [ "data1", "data2", "data3" ];
 	foreach ($list as $value){
 		print $value . "\n";
 	}

 	$hash = [ "kay1" => "data1", "key2" => "data2", "key3" => "data3" ];
 	foreach ($hash as $key => $value){
 		print $key . " => " . $value . "\n";
 	}
?>

_ file

<?php
	$fp = fopen("file.txt", "w");
	fputs($fp, "line 1\n");
	fputs($fp, "line 2\n");
	fputs($fp, "line 3\n");
	fclose($fp);

	$fp = fopen("file.txt", "r");
	while ($rec = fgets($fp)){
		$rec = trim($rec);
		print $rec . "\n";
	}
?>

_ regex

<?php
	if (preg_match('/^abc.*def$/', 'abcpoipoidef')){
		print "true\n";
	}

	$wk = preg_replace('/^abc(.*)def$/', 'ABC${1}DEF', 'abcpoipoidef');	# "ABCpoipoiDEF"

	$list = preg_split('/p.*i/', 'abcpoipoidef');				# [ 'abc', 'def' ]
?>

_ string

<?php
	$str = 'abcあいうdef';
	$wk_str = substr($str,1,1);				# 'b'
	$wk_str = substr($str,3,3);				# 'あ'
	$wk_str_utf8 = mb_substr($str,3,1,'UTF-8');		# 'あ'
	$wk_str_utf8 = mb_substr($str,3,3,'UTF-8');		# 'あいう'
	$wk_str = strlen($str);					# 15
	$wk_str_utf8 = mb_strlen($str,'UTF-8');			# 9
	$wk_str_utf16 = mb_convert_encoding($str,'UTF-16');	# 'abcあいうdef' in UTF-16

	$wk_str = '123';
	$wk_int = (int)$wk_str;				# 123

	$wk_str = (string)$wk_int;			# '123'

	$wk_str = '12.34';
	$wk_float = (float)$wk_str;			# 12.34

	$wk_hex = base_convert('123', 10, 16);		# 7b

	$wk = ord('A');					# 65
	$wk = chr(65);					# 'A'
?>

_ function

<?php
	function add($i1, $i2){
		return ($i1 + $i2);
	}

	wk = add(10,20);		# 30
?>

_ try

<?php
	function div($i1, $i2){
		if ($i2 == 0){
			throw new Exception("zero divided");
		}else{
			return ($i1 / $i2);
		}
	}

	try {
		div(1, 0);
	} catch (Exception $e) {
		echo '捕捉した例外: ',  $e->getMessage(), "\n";
	}
?>

_ daytime

<?php
	date_default_timezone_set('Asia/Tokyo');

	$epoch_time = time();
	$str_date_week_time = date('Y/m/d(w) H:i:s', $epoch_time);	# '2016/12/03(6) 16:57:54' <- Sat
	print $str_date_week_time . "\n";

	$epoch_time = $epoch_time + (24 * 60 * 60);
	$str_date_week_time = date('Y/m/d(w) H:i:s', $epoch_time);	# '2016/12/04(0) 16:57:54' <- Sun
	print $str_date_week_time . "\n";

	$epoch_time = mktime(1,2,3,4,5,2016);
	$str_date_week_time = date('Y/m/d(w) H:i:s', $epoch_time);	# '2016/04/05(2) 01:02:03' <- Tue
	print $str_date_week_time . "\n";
?>

_ filesystem

<?php
	error_reporting(0);
	mkdir('NewDir');
	if (file_exists('NewDir')){
		print "NewDir exists" . "\n";
		if (is_file('NewDir')){
			print "NewDir is file" . "\n";
		}
		if (is_dir('NewDir')){
			print "NewDir is dir" . "\n";
		}
	}
	rmdir('NewDir');

	$fp = fopen('file.txt', 'w');
	fputs($fp, "line1\n");
	fclose($fp);
	unlink('file.txt');

	print getcwd() . "\n";

	foreach (scandir('.') as $dir){
		print $dir . "\n";
	}
?>

_ class

<?php
	class MySwitch{
		private $intSw;
		function __construct($value = 0){
			if (func_num_args() == 0){
				$this->intSw = 0;
			}else{
				$this->intSw = $value;
			}
		}
		function turnOn(){
			$this->intSw = 1;
		}
		function turnOff(){
			$this->intSw = 0;
		}
		function isOn(){
			return ($this->intSw == 1);
		}
		function isOff(){
			return (!isOn());
		}
	}

	class MyToggleSwitch extends MySwitch{
		function __construct(){
			parent::__construct();
		}
		function toggle(){
			if (parent::isOn()){
				parent::turnOff();
			}else{
				parent::turnOn();
			}
		}
	}

	$oSw = new MySwitch();

	if ($oSw->isOn()){
		print "oSw is ON\n";
	}else{
		print "oSw is OFF\n";
	}

	$oSw->turnOn();

	if ($oSw->isOn()){
		print "oSw is ON\n";
	}else{
		print "oSw is OFF\n";
	}

	$oToggleSw = new MyToggleSwitch;

	if ($oToggleSw->isOn()){
		print "oToggleSw is ON\n";
	}else{
		print "oToggleSw is OFF\n";
	}

	$oToggleSw->toggle();

	if ($oToggleSw->isOn()){
		print "oToggleSw is ON\n";
	}else{
		print "oToggleSw is OFF\n";
	}
?>

_ sqlite

<?php
	error_reporting(0);
	$dbfile = 'sqlite.db';
	unlink($dbfile);
	$conn = new SQLite3($dbfile);

	print "テーブルを作成する\n";
	$result = $conn->exec("
		create table t_test (
			id text primary key,
			name text,
			syozoku text
		)
	");
	if (!$result){
		print "テーブル作成出来ません " . $conn->lastErrorMsg() . "\n";
	}

	print "テーブルを作成する2\n";
	$result = $conn->exec("
		create table t_test (
			id text primary key,
			name text,
			syozoku text
		)
	");
	if (!$result){
		print "テーブル作成出来ません " . $conn->lastErrorMsg() . "\n";
	}

	print "初期データセットアップ\n";
	$conn->exec("begin");

	$init_data = [ ['001', '山田 太郎', '本社'],
		       ['002', '山田 花子', '営業第1課'],
		       ['003', '山田 次郎', '営業第2課']];

	$stmt = $conn->prepare("
		insert into t_test
			(id, name, syozoku)
			values(:id, :name, :syozoku)
	");
	if (!$stmt){
		print "ステートメントエラー " . $conn->lastErrorMsg() . "\n";
	}

	foreach ($init_data as $array){
		$stmt->reset();
		$stmt->clear();
		$stmt->bindValue(':id', $array[0] ,SQLITE3_TEXT);
		$stmt->bindValue(':name', $array[1] ,SQLITE3_TEXT);
		$stmt->bindValue(':syozoku', $array[2] ,SQLITE3_TEXT);
		$result = $stmt->execute();
		if (!$result){
			print "追加出来ません " . $conn->lastErrorMsg() . ", ";
			$stmt->reset();
			print $conn->lastErrorMsg() . "\n";
		}else{
			$result->finalize();
		}
	}

	$conn->exec("commit");

	print "初期データセットアップ2\n";
	$conn->exec("begin");

	$init_data = [ ['001', '山田 太郎', '本社'],
		       ['002', '山田 花子', '営業第1課'],
		       ['003', '山田 次郎', '営業第2課']];

	$stmt = $conn->prepare("
		insert into t_test
			(id, name, syozoku)
			values(:id, :name, :syozoku)
	");
	if (!$stmt){
		print "ステートメントエラー " . $conn->lastErrorMsg() . "\n";
	}

	foreach ($init_data as $array){
		print $array[0] . "," . $array[1] . "," . $array[2] . "\n";
		$stmt->reset();
		$stmt->clear();
		$stmt->bindValue(':id', $array[0] ,SQLITE3_TEXT);
		$stmt->bindValue(':name', $array[1] ,SQLITE3_TEXT);
		$stmt->bindValue(':syozoku', $array[2] ,SQLITE3_TEXT);
		$result = $stmt->execute();
		if (!$result){
			print "追加出来ません " . $conn->lastErrorMsg() . ", ";
			$stmt->reset();
			print $conn->lastErrorMsg() . "\n";
		}else{
			$result->finalize();
			$stmt->reset();
		}
		$stmt->clear();
	}

	$conn->exec("commit");

	print "全件検索\n";
	$conn->exec("begin");
	$stmt = $conn->prepare("select * from t_test");
	if (!$stmt){
		print "ステートメントエラー " . $conn->lastErrorMsg() . "\n";
	}
	$result = $stmt->execute();
	while($array = $result->fetchArray()){
		fprintf(STDOUT,"%s,%s,%s\n",$array['id'],$array['name'],$array['syozoku']);
	}

	print "~課のみ検索\n";
	$stmt = $conn->prepare("select * from t_test where syozoku like :syozoku");
	if (!$stmt){
		print "ステートメントエラー " . $conn->lastErrorMsg() . "\n";
	}
	$stmt->reset();
	$stmt->clear();
	$stmt->bindValue(':syozoku', '%課' ,SQLITE3_TEXT);
	$result = $stmt->execute();
	while($array = $result->fetchArray()){
		printf("%s,%s,%s\n",$array['id'],$array['name'],$array['syozoku']);
	}

	print "id=001を山田 三郎に更新\n";
	$stmt = $conn->prepare("update t_test set name = :name where id = :id");
	if (!$stmt){
		print "ステートメントエラー " . $conn->lastErrorMsg() . "\n";
	}
	$stmt->reset();
	$stmt->clear();
	$stmt->bindValue(':name', '山田 三郎' ,SQLITE3_TEXT);
	$stmt->bindValue(':id', '001' ,SQLITE3_TEXT);
	$result = $stmt->execute();

	$stmt = $conn->prepare("select * from t_test where id = :id");
	if (!$stmt){
		print "ステートメントエラー " . $conn->lastErrorMsg() . "\n";
	}
	$stmt->reset();
	$stmt->clear();
	$stmt->bindValue(':id', '001' ,SQLITE3_TEXT);
	$result = $stmt->execute();
	while($array = $result->fetchArray()){
		printf("%s,%s,%s\n",$array['id'],$array['name'],$array['syozoku']);
	}

	$conn->exec("commit");

	print "id=002を削除\n";
	$conn->exec("begin");
	$stmt = $conn->prepare("delete from t_test where id = :id");
	if (!$stmt){
		print "ステートメントエラー " . $conn->lastErrorMsg() . "\n";
	}
	$stmt->reset();
	$stmt->clear();
	$stmt->bindValue(':id', '002' ,SQLITE3_TEXT);
	$result = $stmt->execute();

	$stmt = $conn->prepare("select * from t_test");
	if (!$stmt){
		print "ステートメントエラー " . $conn->lastErrorMsg() . "\n";
	}
	$result = $stmt->execute();
	while($array = $result->fetchArray()){
		printf("%s,%s,%s\n",$array['id'],$array['name'],$array['syozoku']);
	}

	print "ロールバック\n";
	$conn->exec("rollback");

	print "全件検索\n";
	$conn->exec("begin");
	$stmt = $conn->prepare("select * from t_test");
	if (!$stmt){
		print "ステートメントエラー " . $conn->lastErrorMsg() . "\n";
	}
	$result = $stmt->execute();
	while($array = $result->fetchArray()){
		printf("%s,%s,%s\n",$array['id'],$array['name'],$array['syozoku']);
	}

	$conn->exec("commit");

	$conn->close();
	print "終了\n";
?>

_ sqlite実行結果

テーブルを作成する
テーブルを作成する2
テーブル作成出来ません table t_test already exists
初期データセットアップ
初期データセットアップ2
001,山田 太郎,本社
追加出来ません constraint failed, column id is not unique
002,山田 花子,営業第1課
追加出来ません constraint failed, column id is not unique
003,山田 次郎,営業第2課
追加出来ません constraint failed, column id is not unique
全件検索
001,山田 太郎,本社
002,山田 花子,営業第1課
003,山田 次郎,営業第2課
~課のみ検索
002,山田 花子,営業第1課
003,山田 次郎,営業第2課
id=001を山田 三郎に更新
001,山田 三郎,本社
id=002を削除
001,山田 三郎,本社
003,山田 次郎,営業第2課
ロールバック
全件検索
001,山田 三郎,本社
002,山田 花子,営業第1課
003,山田 次郎,営業第2課
終了