查詢及列出資料

建立 SQL 資料表

①district_tw, ②status_affect

設定 SQL 語法
$tb_af='status_affect';
$sql="SELECT * FROM $tb_af ORDER BY id";
創建 PDOstatement 物件
$stmt1=$prime->prepare($sql);
執行 prepare statement
$stmt1->execute();
抓出一筆資料
$row=$stmt1->fetch();
#$row=$stmt1->fetch(PDO::FETCH_OBJ);
#$row=$stmt1->fetch(PDO::FETCH_LAZY);
#$row=$stmt1->fetch(PDO::FETCH_BOTH);
#$row=$stmt1->fetch(PDO::FETCH_ASSOC);
#$row=$stmt1->fetch(PDO::FETCH_NUM);
逐筆抓出並列出資料
$stmt1->execute();
echo '<ol>';
while($row=$stmt1->fetch(PDO::FETCH_OBJ)){
 echo "<li>$row->id, $row->affect</li>";
}
echo '</ol>';
資料列出成 <select> 下拉選項
無預選項
$stmt1->execute();
echo '<label for="affect">感情:</label><select id="affect" name="affect"><option value="0">狀況</option>';
while($row=$stmt1->fetch(PDO::FETCH_OBJ)){
 printf('<option value="%s">%s</option>',$row->id, $row->affect);
#echo "<option value=\"$row->id\">$row->affect</option>";
}
echo '</select>';
加預選項 (selected)
$selected=2;
$stmt1->execute();
echo '<label for="affect">感情:</label><select id="affect" name="affect"><option value="0">狀況</option>';
while($row=$stmt1->fetch(PDO::FETCH_OBJ)){
 printf('<option value="%s"%s>%s</option>',$row->id,$row->id==$selected?' selected':'', $row->affect);
}
echo '</select>';
增加執行成功檢驗
if($stmt1->execute()){
 echo '<label for="affect">感情:</label><select id="affect" name="affect"><option value="0">狀況</option>';
 while($row=$stmt1->fetch(PDO::FETCH_OBJ)){
  printf('<option value="%s">%s</option>',$row->id, $row->affect);
 }
 echo '</select>';
}
除錯:增加例外錯誤發生的處理
$tb_af='status_affect';
$sql="select * from $tb_af ORDER BY id";
try{
 $stmt1=$prime->prepare($sql);
 if($stmt1->execute()){
  echo '<label for="affect">感情:</label><select id="affect" name="affect"><option value="0">狀況</option>';
  while($row=$stmt1->fetch(PDO::FETCH_OBJ)){
   printf('<option value="%s">%s</option>',$row->id, $row->affect);
  }
  echo '</select>';
 }
}
catch(PDOException $e){
 echo $e->getMessage();
 exit;
}
參考資源

更新日期:

google 論壇

App javascript (groups.google.com/group/app-javascript/)