SQLite3

[PHP]INSERT文を作る

INSERT文を作る

echo getInsertQueryByKey('system_table', array('name','gender'), array( array('jeff','male'), array('pola','female') ) );

function getInsertQueryByKey($tableName,$columns,$datas){

	//SQLite古いバージョン
	$w=array();

	$column = implode(',', $columns);
	$query="INSERT INTO {$tableName} ({$column}) SELECT ";
	$tmp=array();
	foreach ($columns as $index => $columnName) {
		$tmp[] = "'". $datas[0][$index] . "'" . ' AS ' . $columnName;
	}
	$query .= implode(', ', $tmp);
	$w[]=$query;

	foreach ($datas as $index => $data) {
		if($index<1)continue;
		$tmp=array();
		foreach ($columns as $index2 => $columnName) {
			$tmp[]=$data[$index2];
		}
		$w[]="'".implode("', '", $tmp)."'";
	}

	return implode(' UNION ALL SELECT ', $w).';';

	/* MySQL or SQLite(バージョン 3.7.11以降)
	$queryValues=array();
	foreach ($datas as $index => $value) {
		$values=array();
		foreach ($value as $index2 => $value2) {
			$values[]="'".$value2."'";
		}
		$queryValues[]='('.implode(',', $values).')';
	}

	$column=implode(',', $columns);
	$value=implode(',', $queryValues);
	$sql="INSERT INTO {$tableName} ({$column}) VALUES {$value};";
	return $sql;
	*/
}

[MySQL,SQLite]INSERTで複数のデータを挿入

INSERTで複数のデータを挿入

INSERT INTO system_table (name,gender) SELECT 'jeff' AS name, 'male' AS gender UNION ALL SELECT 'pola', 'female';

MySQL or SQLite(バージョン 3.7.11以降)

INSERT INTO system_table (name,gender) VALUES ('jeff','male'),('pola','female');

[PHP x SQLite3]PHPでSQLite3 #5データ更新(UPDATE)

PHPでSQLite3 #5データ更新(UPDATE)

$sql="SELECT id,cnt FROM $tableName WHERE id='{$id}'";
$result=$db->query($sql);
$row = $result->fetchArray();
$id=$row['id'];
$cnt=$row['cnt']+1;

$sql="UPDATE $tableName SET cnt = $cnt WHERE id = $id";
$result=$db->query($sql);

[PHP x SQLite3]PHPでSQLite3 #3データ取得(SELECT)

PHPでSQLite3 #3データ取得(SELECT)

$tableName="access";
$sql="SELECT id,name,cnt FROM $tableName WHERE name='{$name}' ORDER BY cnt ASC";
$result=$db->query($sql);
$tmp=[];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
	$tmp[]=$row;
}
echo json_encode($tmp);
$db->close();

データ重複しないように取得

$sql="SELECT DISTINCT name FROM $tableName";
$result=$db->query($sql);
if($result===FALSE){
	$db->close();
	echo $message;
	exit;
}
$tmp=[];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
	$value=$row['name'];
	$tmp[]=$value;
}
echo json_encode($tmp);

[PHP x SQLite3]PHPでSQLite3 #2テーブル作成

PHPでSQLite3 #2テーブル作成

$tableName="access";
$sql="create table if not exists $tableName (id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(6), title text, cnt int)";
$result=$db->query($sql);
if ($result===FALSE) {
	$db->close();
	echo $message;
	exit;
}
$db->close();