xml connect with MySQL

<?php 

$database = "nameofthedatabase"
$dbconnect = mysql_pconnect(localhost, dbuser, dbpassword);
mysql_select_db($database, $dbconnect);
$query = "select link, headline, description from 'headlines' limit 15";
$result = mysql_query($query, $dbconnect);

while ($line = mysql_fetch_assoc($result))
  {
    $result&#91;&#93; = $line;
  }
$now = date("D, d M Y H:i:s T");

$output = "<?xml version=\"1.0\"?>
        <rss version=\"2.0\">
          <channel>
            <title>Our Demo RSS</title>
            <link>http://wwww.tracypeterson.com/RSS/RSS.php</link>
            <description>A TEST RSS</description>
            <language>en-us</language>
            <pubDate>$now</pubDate>
            <docs>http://someurl.com</docs>
            <managingEditor>yo@youremail.com<managingEditor>
            <webMaster>you@youremail.com</webMaster>
          ";
foreach ($return as $line)
{
  $output .= "<item><title>".htmlentities($line['headline'])."</title>
              <link>".htmlentities($line['link'])."</link>

  <description>".htmlentities(strip_tags($line['description']))."</description>
      </item>";
}
$output .= "</channel></rss>";
echo $output;
?>
<?php
// ヘッダーを出力する
header("Content-type: text/xml;charset=utf-8");
echo '<?xml version="1.0" encoding="UTF-8"?>';

// サイト情報を書き込む
echo '
<rss version="2.0">
<channel>
<title>hogehogeオレオレRSS</title>
<link>http://google.com</link>
<description>Facebookのgraph api, cake php, javascriptなどの記事を更新していきます。</description>
<category>php, graph api, facebook, cakephp</category>
<generator>@DAI199</generator>
<webMaster>@DAI199</webMaster>
';

// 記事の内容を更新
for(ループさせる)
{
echo '
<item>
<title>Test'.$i.'</title>
<link>http://google.com</link>
<description>TestTest</description>
<author>@DAI199</author>
<category>php</category>
</item>
';
}

echo '
</channel>
</rss>
';
?>

make a xml file4

<?php
 // ライブラリの読み込み
 require_once './Feed.php';

 // 取得するフィードのurl指定
 $url = "http://www.lesson5.info/?feed=rss2" ;

 // インスタンスの作成
 $feed = new Feed;

 // RSS読み込み
 $rss = $feed->loadRss( $url );

 // HTML表示用
 $html = '';
 $sitename = $rss->title ;

foreach( $rss->item as $item )
{
  // 各エントリーの処理
  $title = $item->title; //タイトル
  $link = $item->link ; //リンク

  // 日付の取得(unix timestamp)
  foreach( array( "pubDate", "date_timestamp", "dc:date", "published", "issued" ) as $time )
  {
    if ( isset( $item->{ $time }) && !empty( $item->{ time }))
    {
      $timestamp = ( is_int( $item->{ $time })) ? $item->{ $time }: strtotime( $item->{ $time });
      break ;
    }
  }

  //仮に日付が取得できなかったら現在時刻
  if( !isset( $timestamp ))
  {
    $timestamp = time();
  }
  $html .= '<dt><a href="' . $link . '" traget="_blank">' . $title . '</a>(' . date( "Y/m/d" , $timestamp).')</dt></dd>' . $sitename .'</dd>';
}
?>

<dl>
  <?php echo $html ?>
</dl>
<?php
 // ライブラリの読み込み
 require_once './Feed.php';

 // キャッシュの設定
 Feed::$cacheDir = './temp';
 Feed::$cacheExpire = '1 hours';

 // html表示用
 $html = '';

 // 表示最大件数
 $maxview = 5;

 // 取得するフィードのurl指定
 $urls = array(
   "http://www.lesson5.info/?feed=rss2",
   "http://www.lesson5.info/?feed=rss2",
   "http://www.lesson5.info/?feed=rss2",
   "http://www.lesson5.info/?feed=rss2",
   "http://www.lesson5.info/?feed=rss2",
   "http://www.lesson5.info/?feed=rss2"
 );

 // 各rssをまとめた配列
 $entrylist = array();

 for ($i = 0; $i < count($urls); $i++){
   $url = $urls&#91;$i&#93;;

 // インスタンスの作成
 $feed = new Feed;

 // RSS読み込み
 $rss = Feed::loadRss($url);

 for ($entry = 0; $entry < 1; $entry++){
   $sitename = $rss->title;
   $sitelink = $rss->link;
   $item = $rss->item[$entry];
   // 各エントリーの処理
   $title = $item->title ;
   $link = $item->link ;
   $timestamp = strtotime($item->pubDate);
   // 配列に
   $entrylist[$i]['sitename'] = $sitename;
   $entrylist[$i]['sitelink'] = $sitelink;
   $entrylist[$i]['title'] = $title;
   $entrylist[$i]['link'] = $link;
   $entrylist[$i]['timestamp'] = $timestamp;
 }
 }

 // 日付でソート
 foreach ((array)$entrylist as $key => $value){
   $sort[$key] = $value['timestamp'];
 }
 array_multisort($sort, SORT_DESC, $entrylist);

 if ( count($entrylist) > $maxview ){
   $entrynum = $maxview;
 } else {
   $entrynum = count($entrylist);
 }
 for ($i = 0; $i < $entrynum; $i++){
   $html .= '<dt><a href="' . $entrylist&#91;$i&#93;&#91;'link'&#93; . '" target="_blank">' . $entrylist[$i]['title'] . '</a> (' . date( "Y/m/d" , $entrylist[$i]['timestamp'] ) . ')</dt><dd><a href="' . $entrylist&#91;$i&#93;&#91;'sitelink'&#93; . '" target="_blank">' . $entrylist[$i]['sitename'] . '</a></dd>' ;
 }
?>

<dl>
  <?php echo $html ?>
</dl>

make a xml file2

<?php

  /* rss用フィードを作成するcgiファイル
  * index.html, atom.xml, index.rdf
  */

  $RSS_FEED_NUM = 10; // RSSのフィード数

  //1 . RSSヘッダー作成
  $rss = '';
  $rss = $rss . '<?xml version="1.0" encoding="utf-8" ?>';
  $rss = $rss . '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" '
              . 'xmlns:content="http://purl.org/rss/1.0/modules/content/" xml:lang="ja">';
  $rss = $rss . '<channel>';
  $rss = $rss . '<title>YoheiM.NET - 世の中をさらに便利に面白く</title>';
  $rss = $rss . '<link>http://www.yoheim.net/</link>';
  $rss = $rss . '<description>YoheiM.NET - 世の中をさらに便利に、面白く</description>';
  $rss = $rss . '<dc:creator>yoheiM</dc:creator>';

  //2. RSSのデータ部分を好きな数だけ作成する。今回は10個。

  // フィードに出力するファイルパスの配列を取得
  $file_list = getFeedList();

  // FEED数分作成する
  for ($i = 0; $i < $RSS_FEED_NUM; $i++){

    // ブログタイトルを取得
    $fPath = $file_list&#91;$i&#93;;
    $f = fopen($fPath, "rb");
    $title = fgets($f);
    fclose($f);
    $title = getTitle($fPath);

    // blog urlを取得
    $blogURL = getURL($fPath);

    // ブログの中身を取得する
    $content = '';
    $fPath = $file_list&#91;$i&#93;;
    $fp = fopen($fPath, "rb");
    while (!feof($fp)){
      $buf = fgets($fp);
      $content = $content . $buf;
    }
    fclose($fp);

    // 作成日時を作成
    // ファイルの更新日時を使う
    date_default_timezone_set('Asia/Tokyo');
    $pubDate = date("D, d M Y H:i:s", filetime($fPath));

    // Feed作成
    $item = '';
    $item = $item . '<item>';
    $item = $item . '<title>' . $title . '</title>';
    $item = $item . '<link>' . $blogURL . '</link>';
    $item = $item . '<description><!&#91;CDATA&#91;';
    $item = $item . $content;
    $item = $item . '&#93;&#93;></description>';
    $item = $item . '<dc:creator>yoheiM</dc:creator>';
    $item = $item . '<pubDate>'. $pubDate . '</pubDate>';
    $item = $item . '</item>';

    $rss = $rss . $item;
  }

  // 3, RSSの絞めタグなどを作成
  $rss = $rss . '</channel>';
  $rss = $rss . '</rss>';

  // 4, RSSファイルとして認識されうるファイルを3個くらい出力
  $f = fopen("index.xml", "wb");
  fwrite($f, $rss);
  fclose($f);

  $f = fopen("atom.xml", "wb");
  fwrite($f, $rss);
  fclose($f);

  $f = fopen("index.rdf", "wd");
  fwrite($f, $rss);
  fclose($f);

  // end
  echo "OK\n";
?>

make a xml file

<?php
include_once './RssFeed.php';
include_once './RssItem.php';

$rss = new RssFeed();
$rss->title('サイトタイトル');
$rss->description('サイトの説明文です');
$rss->link('http://example.com/');
$rss->atomLink('http://example.com/rss.xml');

$item = new RssItem();
$item->title('記事1');
$item->description('ここに要約が入ります');
$item->link('http://example.com/1');
$item->guid('http://example.com/1');
$item->pubDate('2016-01-02 12:23:34');
$rss->addItem($item);

header('Content-type:application/rss+xml');
echo $rss->saveXML();
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>サイトタイトル</title>
    <description><!&#91;CDATA&#91;サイトの説明文です&#93;&#93;></description>
    <link>http://example.com/</link>
    <atom:link href="http://example.com/rss.xml" rel="self" type="application/rss+xml"/>
    <item>
      <title>記事1</title>
      <description><!&#91;CDATA&#91;ここに要約が入ります&#93;&#93;></description>
      <link>http://example.com/1</link>
      <guid isPermaLink="true">http://example.com/1</guid>
      <pubDate>Sat, 02 Jan 2016 12:23:34 +0900</pubDate>
    </item>
  </channel>
</rss>

file_put_contents($file, $xml);

RSS1.0
シンプルな記述。テキスト配信向き
RDFシリーズを元にして制作。
はてなRSSは1.0。FC2も1.0。
RSS2.0
配信する文章の色を変えたり、リンクを仕込めるなど、グラフィック面でいろいろ出来る。コンテンツ配信向き
XMLシリーズを元にして制作されている。

<?php

	// ライブラリの読み込み
	require_once "./Item.php" ;
	require_once "./Feed.php" ;
	require_once "./RSS2.php" ;

	// エイリアスの作成
	use \FeedWriter\RSS2 ;

	// インスタンスの作成
	$feed = new RSS2 ;

	// チャンネル情報
	$feed->setTitle( "SYNCER" ) ;			// チャンネル名
	$feed->setLink( "https://syncer.jp" ) ;		// URLアドレス
	$feed->setDescription( "知識と感動を同期(Sync)するブログ" ) ;	// チャンネル紹介テキスト
	$feed->setImage( "SYNCER" , "https://syncer.jp","https://syncer.jp/images/DHFgXv5Rfe4d1Lej1lnQfuffZtzsj/assets/logo/490x196.png" ) ;	// ロゴなどの画像
	$feed->setDate( date( DATE_RSS , time() ) ) ;	// フィードの更新時刻
	$feed->setChannelElement( "language" , "ja-JP" ) ;	// 言語
	$feed->setChannelElement( "pubDate" , date(\DATE_RSS, strtotime("2014-11-23 15:30")) ) ;	// フィードの変更時刻
	$feed->setChannelElement( "category" , "Blog" ) ;	// カテゴリー

	// アイテム(1つだけ登録)
	$item = $feed->createNewItem() ;
	$item->setTitle( "PHPでRSS、AtomのFeedを作成する方法" ) ;	// タイトル
	$item->setLink( "https://syncer.jp/how-to-make-feed-by-php" ) ;	// リンク
	$item->setDescription( "PHPを使って、RSS、Atomのフィード・ファイルを作成する方法を解説します。" ) ;	// 紹介テキスト
	$item->setDate( strtotime("2014-11-23 18:30") ) ;	// 更新日時
	$item->setAuthor( "あらゆ" , "info@syncer.jp" ) ;	// 著者の連絡先(E-mail)
	$item->setId( "https://syncer.jp/how-to-make-feed-by-php" , true ) ;	// 一意のID(第1引数にURLアドレス、第2引数にtrueで通常は大丈夫)
	$feed->addItem( $item ) ;

	// コードの生成
	$xml = $feed->generateFeed() ;

	// ファイルの保存場所を設定
	$file = "./rss2_2.xml" ;

	// ファイルの保存を実行
	@file_put_contents( $file , $xml ) ;
<rss version="2.0">
<channel>
<title>SYNCER</title>
<link>https://syncer.jp</link>
<description>
<!&#91;CDATA&#91; 知識と感動を同期(Sync)するブログ &#93;&#93;>
</description>
<image>
<title>https://syncer.jp</title>
<link>
https://syncer.jp/images/DHFgXv5Rfe4d1Lej1lnQfuffZtzsj/assets/logo/490x196.png
</link>
<url>SYNCER</url>
</image>
<lastBuildDate>Wed, 14 Dec 2016 21:30:07 +0900</lastBuildDate>
<language>ja-JP</language>
<pubDate>Sun, 23 Nov 2014 15:30:00 +0900</pubDate>
<category>Blog</category>
<item>
<title>PHPでRSS、AtomのFeedを作成する方法</title>
<link>https://syncer.jp/how-to-make-feed-by-php</link>
<description>
<!&#91;CDATA&#91; PHPを使って、RSS、Atomのフィード・ファイルを作成する方法を解説します。 &#93;&#93;>
</description>
<pubDate>Sun, 23 Nov 2014 18:30:00 +0900</pubDate>
<author>info@syncer.jp (あらゆ)</author>
<guid isPermaLink="true">https://syncer.jp/how-to-make-feed-by-php</guid>
</item>
</channel>
</rss>

Insert DB-API

Inserts in DB API

pg = psycopg2.connect("dbname=somedb")
c = pg.cursor()
c.execute("insert into names values('Jennifer Smith')")

pg.commit()



import sqlite3

db = sqlite3.connect("testdb")
c = db.cursor()
c.execute("insert into balloons values ('blue', 'water') ")
db.commit()
db.close()

DB data attack
‘); delete from posts;–

spam table

<script>
setTimeout(function() {
    var tt = document.getElementById('content');
    tt.value = "<h2 style='color: #FF6699; font-family: Comic Sans MS'>Spam, spam, spam, spam,<br>Wonderful spam, glorious spam!</h2>";
    tt.form.submit();
}, 2500);
</script>

Python DB-API

Python DB-API is a library method call sqlite and data.

writing DB-API

import sqlite3
conn = sqlite3.connect("Cookies")
cursor = conn.cursor()
cursor.execute(
    "select host_key from cookies limit 10")

results = cursor.fetchall()
print results
conn.close()

Watch how DB-API work below.

import sqlite3

# Fetch some student records from the database.
db = sqlite3.connect("students")
c = db.cursor()
query = "select name, id from students;"
c.execute(query)
rows = c.fetchall()

# First, what data structure did we get?
print "Row data:"
print rows

# And let's loop over it too:
print
print "Student names:"
for row in rows:
  print "  ", row[0]

db.close()

Result
Row data:
[(u’Jade Harley’, 441304), (u’Harry Evans-Verres’, 172342), (u’Taylor Hebert’, 654321), (u’Diane Paiwonski’, 773217), (u’Melpomene Murray’, 102030), (u’Robert Oliver Howard’, 124816), (u’Hoban Washburne’, 186753), (u’Trevor Bruttenholm’, 162636), (u’Jonathan Frisby’, 917151)]

Student names:
Jade Harley
Harry Evans-Verres
Taylor Hebert
Diane Paiwonski
Melpomene Murray
Robert Oliver Howard
Hoban Washburne
Trevor Bruttenholm
Jonathan Frisby

order by [ASC | DESC]

sql join on

QUERY = '''
select animals.name 
from animals join diet on animals.species = diet.species
where food = 'fish';
'''

having

QUERY = '''
select species, count(*) as num 
from animals group by species
having num = 1;
'''
QUERY = '''
select species, count(*) as num 
from animals group by species
having num = 1;
'''

QUERY = '''
select diet.food, count(*) as num
from animals join diet on animals.species = diet.species
group by food
having num = 1;
'''

python sql

QUERY = '''
select name, birthdate from animals where species = 'gorilla';
'''

+———+————+
| name | birthdate |
+=========+============+
| Max | 2001-04-23 |
| Dave | 1988-09-29 |
| Becky | 1979-07-04 |
| Liz | 1998-06-12 |
| George | 2011-01-09 |
| George | 1998-05-18 |
| Wendell | 1982-09-24 |
| Bjorn | 2000-03-07 |
| Kristen | 1990-04-25 |
+———+————+

select name, birthdate from animals where species = ‘gorilla’ and name = ‘Max’

否定

QUERY = '''
select name, birthdate from animals where species != 'gorilla' and name != 'Max';
'''

between文

QUERY = '''
select name from animals where species = 'llama' AND birthdate between '1995-01-01' AND '1998-12-31';
'''

query

QUERY = "select max(name) from animals;"

QUERY = "select * from animals limit 10;"

QUERY = "select * from animals where species = 'orangutan' order by birthdate;"

QUERY = "select name from animals where species = 'orangutan' order by birthdate desc;"

QUERY = "select name, birthdate from animals order by name limit 10 offset 20;"

QUERY = "select species, min(birthdate) from animals group by species;"

QUERY = '''
 select name, count(*) as num from animals
 group by name
 order by num desc
 limit 5;
 '''

Limit count Offset skip
limit is how many rows to return
offset is how far into the results to start

Order by columns DESC
columns is which columns to sort by, separated with commas
DESC is sort in reverse order(descending)

Group by columns
columns is which columns to use as groupings when aggregating

QUERY = "select count(*) as num, species from animals group by species order by num desc;"

insert

INSERT_QUERY = '''
insert into animals (name, species, birthdate) values ('yoshi', 'opposum', '2016-12-13');
'''