1. TOPTOP
  2. Webサービス
  3. Twitter

Twitterの画像を格納するためのクエリ文とPHPコード。”NULL”と”Notice: Undefined offset”について

Twitter_logo_blue

昨年末、Twitterのツイートに付属する画像処理に関する記事を書きました。

この記事のポイントは、画像の縮小とデータベースへの保存です。これらのうち、データベースへの保存に関するコードが出来上がったのでのせておきます。

Twitterの画像を格納するクエリ文とPHPコード

ツイート本文と画像4枚を格納するテーブル

データベースを保存する作業なので、まずテーブルの作成です。保存するデータは、ツイート本文と画像4枚を想定します。4枚というのは、Twitterの仕様として決まっている数(新しいタブで開く)のことです。

create table tweet_add_img (
	id int(11) not null auto_increment primary key,
	tw_txt text,
	tw_img0 varchar(256) default "",
	tw_img1 varchar(256) default "",
	tw_img2 varchar(256) default "",
	tw_img3 varchar(256) default ""
);

ツイートを取得したからといっても、必ずしも画像が添付されているとは限りません。従って、画像のカラムはデフォルト値として空文字を設定しています。

ツイート本文と画像4枚を取得するPHPコード

ユーザータイムラインで1件のツイート本文と画像4枚を取得します。

require_once("twitteroauth/twitteroauth.php");

$consumerKey = "MYCONSUMERKEY";
$consumerSecret = "MYCONSUMERSECRET";
$accessToken = "MYACCESSTOKEN";
$accessTokenSecret = "MYACCESSTOKENSECRET";

$twObj = new TwitterOAuth($consumerKey,$consumerSecret,$accessToken,$accessTokenSecret);

$request = $twObj->OAuthRequest('https://api.twitter.com/1.1/statuses/user_timeline.json','GET',
    array(
        'count'=>'1',
        'screen_name' => 'echizenya_yota',
        ));
$results = json_decode($request);

if(isset($results) && empty($results->errors)){
	foreach($results as $tweet){
		// データベースの接続
		try {
		 	$dbh = new PDO('mysql:host=localhost;dbname=tweet1;charset=utf8', 'myusername','mypassword');
		} catch(PDOException $e) {
		 	var_dump($e->getMessage());
		 	exit;
		}

		// 処理
		$stmt = $dbh->prepare(
			"insert into tweet_add_img (
				tw_txt,
				tw_img0,
				tw_img1,
				tw_img2,
				tw_img3
				)
				values (
				:tw_txt,
				:tw_img0,
				:tw_img1,
				:tw_img2,
				:tw_img3
				)"
			);
		$stmt->execute(
			array(
				":tw_txt" => $tweet->text,
				":tw_img0" => $tweet->extended_entities->media[0]->media_url,
				":tw_img1" => $tweet->extended_entities->media[1]->media_url,
				":tw_img2" => $tweet->extended_entities->media[2]->media_url,
				":tw_img3" => $tweet->extended_entities->media[3]->media_url
				)
			);

		// 切断
		$dbh = null;
	}
  }else{
	echo "関連したつぶやきがありません。";
 }

echo "done!";

問題点

必要な方は、これらのコピペをしていただいても構わないのですが、問題点が2か所あると考えています。

画像のカラムにNULL

tw_add_img1

例として、2枚の添付画像がついているツイートの取得を想定しています。画像のカラムである、tw_img2とtw_img3を注目するとNULLの2文字が。

テーブルの設計として空文字を指定した割にはいかがなものか?と、「ひとりつっこみ」をせざるを得ません。

Notice: Undefined offset

tw_add_img2

Notice: Undefined offsetとは、3番目と4番目のオブジェクトが設定されていないという、注意喚起でしょう。

これらはPHPのエラーレベルを落とすことで、無視していいものなのでしょうか?何とも煮え切らない中途半端な状態なんで、詳しい方にオフライン上で確認しておきます。

〔参考サイト〕