Monthly Archives: 2月 2017

「JavaScript入門」SelectオブジェクトとOptionオブジェクトの使い方

1.Selectオブジェクトの作成
function createSelect(){
Select = document.createElement(“select”);
diastSelect.id = “diastSelect”;
document.body.appendChild(diastSelect);
}

2.optionを追加
function addOption(){
//idによってオブジェクトを検索
var obj=document.getElementById(‘diastSelect’);
// optionを追加
obj.options.add(new Option(“text”,”value”));
}
3.すべてのoptionを削除
function removeAll(){
var obj=document.getElementById(‘diastSelect’);
obj.options.length=0;
}
4.一つのoptionを削除
function removeOne(){
var obj=document.getElementById(‘diastSelect’);
var index=obj.selectedIndex;
obj.options.remove(index);
}
5.optionの値を取得
var obj=document.getElementById(‘diastSelect’);
var index=obj.selectedIndex; //選択されたoptionのシリアル番号
var val = obj.options[index].value;

6.optionのtextを取得
var obj=document.getElementById(‘diastSelect’);
var index=obj.selectedIndex; //選択されたoptionのシリアル番号
var val = obj.options[index].text;

7.optionを修正
var obj=document.getElementById(‘diastSelect’);
var index=obj.selectedIndex;
var val = obj.options[index]=new Option(“newtextVal”,”newVal”);

8.selectを削除
function removeSelect(){
var diastSelect = document.getElementById(“diastSelect”);
diastSelect.parentNode.removeChild(diastSelect);
}

「PHP+MySQL」PDOでデータを更新するサンプル

1. 1つのレコードで複数のフィールドを更新
phpコード:
$sql = “UPDATE students SET age = :age, hobby = :hobby WHERE stuid = :stuid”;
$stmt = $con->prepare($sql);
$stuArr = array(‘:age’ => ’21’, ‘:hobby’ => ‘game’, ‘:stuid’ => ‘1002’);
$stmt->execute($stuArr);

2.複数のフィールドとレコードを更新
phpコード:
$sql = “UPDATE students SET age = :age, hobby = :hobby WHERE stuid = :stuid”;
$stmt = $conn->prepare($sql);
$stuArr = array(
array(‘age’=>’20’, ‘hobby’=>swim, ‘stuid’=>1003),
array(‘age’=>’21’, ‘hobby’=>game, ‘stuid’=>1002),
);

// foreachループ処理
foreach ($stuArr as $row) {
$stmt->execute(array(
‘:age’ => $row[‘age’],
‘:hobby’ => $row[‘hobby’],
‘:stuid’ => $row[‘stuid’])
);

「iOS入門」Core Dataの使い方

コード:
1.contextを取得
– (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
2.データを追加
NSManagedObjectContext *context = [self managedObjectContext];

// Create a new managed object
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@”Device” inManagedObjectContext:context];
[newDevice setValue:self.nameTextField.text forKey:@”name”];
[newDevice setValue:self.versionTextField.text forKey:@”version”];
[newDevice setValue:self.companyTextField.text forKey:@”company”];

NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@”Can’t Save! %@ %@”, error, [error localizedDescription]);
}

3.データを削除
NSManagedObjectContext *context = [self managedObjectContext];

// Delete object from database
[context deleteObject:[self.devices objectAtIndex:indexPath.row]];

NSError *error = nil;
if (![context save:&error]) {
NSLog(@”Can’t Delete! %@ %@”, error, [error localizedDescription]);
return;
}

4.データを修正
NSManagedObjectContext *context = [self managedObjectContext];

// Update existing device
[self.device setValue:self.nameTextField.text forKey:@”name”];
[self.device setValue:self.versionTextField.text forKey:@”version”];
[self.device setValue:self.companyTextField.text forKey:@”company”];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@”Can’t Save! %@ %@”, error, [error localizedDescription]);
}
5. データを検索
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@”Device”];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

詳細内容 http://www.appcoda.com/introduction-to-core-data/

[php入門]pdoのlikeを検索する方法

phpコード:
$db = new PDO(‘mysql:host=localhost;dbname=testdb’, ‘user’, ‘12345’);
$atp = $db->prepare(“select * from memtbl where name like ?”);

$atp->execute(array(‘%qq%’));

// 結果確認
var_dump($atp->fetchAll());

$atp->execute(array(‘qq%’)); // 前方一致
$atp->execute(array(‘%qq’)); // 後方一致
$atp->execute(array(‘qq’)); // 完全一致

「JavaScript入門」同じ画面で複数のbuttonによる動作の振り分け方法

javascriptコード:
<div id=”result”>test content</div>
<div id=”info”>test content</div>
<button id=”btn1″ onclick=”funcFirst()”>button1</button>
<button id=”btn2″ onclick=”funcSecond()”>button2</button>
<script>
function funcFirst() {
document.getElementById(“result”).html=”btn1を押下後コンテンツ”;
}
function funcSecond() {
document.getElementById(“info”).html=”btn2を押下後コンテンツ;
}
</script>

「PHP入門」PDOでPostgresSQLに接続「Error:could not find driver」の解決方法

1.Linuxの場合
yum でインストール
#php -i | grep pdo
#yum install php-pdo_pgsql
2.Windowsの場合(xamppを利用する)
C:\xampp\php\php.ini
修正前
;extension=php_pdo_pgsql.dll
修正後
extension=php_pdo_pgsql.dll
xamppを再起動する

CentOS7.2にphp7をインストールする

1.依存パッケージのインストール
#yum install gcc make crul-devel libxslt-devel gd-devel libjpeg-devel libpng libpng-devel libxml2-devel bzip2-devel libcurl-devel –y
#yum -y install libmcrypt-devel mcytpt mhash libxslt-devel

2.libiconvのインストール
#tar xf libiconv-1.14.tar.gz
#cd libiconv-1.14
#./configure –prefix=/usr/lcoal/libiconv
#make && make install

3.php7のインストール
#tar xf php-7.0.0.tar.gz
#cd php-7.0.0/
./configure \
–prefix=/usr/local/php7 \
–with-fpm-user=nginx \
–with-fpm-group=nginx \
–with-bz2 \
–with-curl \
–with-gd \
–with-mcrypt \
–with-openssl \
–with-mhash \
–with-jpeg-dir \
–with-png-dir \
–with-freetype-dir \
–with-iconv-dir=/usr/local/libiconv \
–with-gettext \
–with-libxml-dir \
–with-zlib \
–with-xmlrpc \
–with-pcre-regex \
–with-pear \
–with-pdo-mysql=mysqlnd \
–with-mysql=mysqlnd \
–with-mysqli=mysqlnd \
–with-libdir=lib64 \
–enable-dom \
–enable-xml \
–enable-fpm \
–enable-bcmath \
–enable-ftp \
–enable-sockets \
–disable-ipv6 \
–enable-mbregex \
–enable-mbstring \
–enable-calendar \
–enable-gd-native-ttf \
–enable-static \
–enable-fpm \
–enable-bcmath \
–enable-libxml \
–enable-inline-optimization \
–enable-mbregex \
–enable-opcache \
–enable-pcntl \
–enable-shmop \
–enable-soap \
–enable-sockets \
–enable-sysvsem \

–enable-zip \
#make && make install
4.設定ファイルのコピー
#cp php.ini-production /usr/local/php7/lib/php.ini
#cp /usr/local/php7/etc/php-fpm.conf.default /usr/local/php7/etc/php-fpm.conf

#cp /usr/local/php7/etc/php-fpm.conf.default /usr/local/php7/etc/php-fpm.conf

「PHP入門」SimpleXMLでxmlドキュメントを作成するサンプル

PHPコード:
<?PHP
$bookArr = array(
array(
‘title’ => ‘how to study spring mvc’,
‘content’ => ‘spring mvc development and sample’,
‘pubdate’ => ‘2016-10-11’,
),
array(
‘title’ => ‘struts2 begin learning’,
‘content’ => ‘Struts2 sample and grammar’,
‘pubdate’ => ‘2015-01-11’,
)
);

// 配列
$propArr = array(
‘title’ => array(
‘size’ => 1
)
);

$strXml = <<<XML
<?xml version=’1.0′ encoding=’utf-8′?>
<article>
</article>
XML;

$xml = simplexml_load_string($strXml);

foreach ($bookArr as $data) {
$item = $xml->addChild(‘item’);
if (is_array($data)) {
foreach ($data as $key => $row) {
$node = $item->addChild($key, $row);

if (isset($propArr[$key]) && is_array($propArr[$key])) {
// foreachループ
foreach ($propArr[$key] as $akey => $aval) {
$node->addAttribute($akey, $aval);
}
}
}
}
}
echo $xml->asXML();
?>

Jersey(JAX-RS)でRESTful API開発–@Producesと @Consumesの使い方

1.Javaコード
@Path(“CompanyInfo”)
public class CompanyInfo {
@GET
@Produces(“application/xml”)
@Consumes(“text/plain”)
public String getXML(@QueryParam(“name”) @DefaultValue(“○○株式会社”) String companyName) throws Exception{
DcoumentBuilderfactory dbf =DocumentBuilderfactory.newInstance();
DocumentBuilder builder =dbf.newDcoumentBuilder();
Document doc = builder.newDocument();

Element element = doc.createElement(“会社”);
element.appendChild(doc.createElement(“開発チーム”));
element.appendChild(doc.createElement(“インフラチーム”));
element.setAttribute(“社名”, companyName);
doc.appendChild(element);

StringWriter strSwr = new StringWriter();
StreamResult strSrt = new StreamResult(strSwr);
TransformerFactory strTfac = TransformerFactory.newInstance();
Transformer tr = strTfac.newTransformer();
tr.transform(new DOMSource(doc.getDocumentElement()),strSrt);
String strRet = strSrt.getWriter().toString();
return strRet;
}
}

2.サーブレット用web.xml
<servlet>
<display-name>JAX-RS REST Servlet</display-name>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>

3.検証URL
http://localhost:8080/rest/services/CompanyInfo
http://localhost:8080/rest/services/CompanyInfo?name=itcompany

「Java入門」スレッド毎のパラメータ値を保持するThreadLocalの使い方

Javaコード:
public class LocalthreadTest {
private static ThreadLocal<Integer> seqTdNum = new ThreadLocal<Integer>() {
public Integer initialValue() {
return 0;
}
};

public int getNextNum() {
seqTdNum.set(seqTdNum.get() + 1);
return seqTdNum.get();

}

public static void main(String[] args) {
LocalthreadTest tm = new LocalthreadTest();
SampleClient t1 = new SampleClient(tm);
SampleClient t2 = new SampleClient(tm);
SampleClient t3 = new SampleClient(tm);
t1.start();
t2.start();
t3.start();
}

private static class SampleClient extends Thread {
private LocalthreadTest ltd;

public SampleClient(LocalthreadTest ltd) {
this.ltd = ltd;
}

public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(“thread[” + Thread.currentThread().getName() + “] –> tm[” + ltd.getNextNum() + “]”);

}
}
}
}
実行結果:
thread[Thread-0] –> tm[1]
thread[Thread-1] –> tm[1]
thread[Thread-2] –> tm[1]
thread[Thread-1] –> tm[2]
thread[Thread-0] –> tm[2]
thread[Thread-1] –> tm[3]
thread[Thread-2] –> tm[2]
thread[Thread-0] –> tm[3]
thread[Thread-2] –> tm[3]