29 สิงหาคม 2554

Smary template แสดงข้อมูล จาก Database

หลังจากได้อ่านบทความต่าง ๆ ของ Smarty template ไปบ้างเล็ก ๆ น้อย ๆ วันนี้จะเป็นการนำข้อมูลจากฐานข้อมูลมาแสดง โดยการส่งข้อมูลออกมาเป็น Array

ซึ่งตัวอย่างในการใช้งานดังต่อไปนี้ :

- สร้างไฟล์ test_2.php ขึ้นมาโดยเขียนโค้ด ด้านล่างลงไป

<?php
require'libs/Smarty.class.php';

$hostname = 'localhost';
$database = 'phithan_appointment';
$user = 'root';
$pass = '';
$connection = mysql_connect($hostname, $user, $pass) or trigger_error(mysql_error(),E_USER_ERROR); //+ เชื่อมต่อฐานข้อมูล
mysql_select_db($database,$connection);
mysql_query("SET NAMES UTF8");

$sql = 'SELECT * FROM tbl_appointment LIMIT 20'; //+ เลือกมาแค่ 20 แถว
$rs_appointment = mysql_query($sql);

while($row_appointment = mysql_fetch_array($rs_appointment)){
$appointment[$row_appointment['app_id']] = $row_appointment['app_customer']; //+ ทำเป็น Array
}

$smarty = new Smarty();
$smarty->assign('appointment', $appointment);
$smarty->display('test_2.tpl'); //+ ส่งข้อมูลออกไปที่ test_2.tpl เืพื่อทำการแสดงข้อมูล
?>

- สร้างไฟล์ test_2.tpl ไว้ภายในโฟลเดอร์ templates แล้วเขียนโ้ค้ดด้านล่างลงไป

<html>
<head>
<title>Test Smary</title>
</head>
<body>
<table>
{foreach from=$appointment key=k item=i}
<tr><td>{$k}</td><td>{$i}</td></tr>
{/foreach}
</table>
</body>
</html>

* key เปรียบได้เป็น index ของ Array และ item คือ Value นั่นเอง


หรือจะเป็นการส่งข้อมูลจากฐานข้อมูลแบบหลาย ๆ คอร์ลัม ดังตัวอย่างด้านล่าง

- ไฟล์ test_2.php

<?php
require'libs/Smarty.class.php';

$hostname = 'localhost';
$database = 'phithan_appointment';
$user = 'root';
$pass = '';
$connection = mysql_connect($hostname, $user, $pass) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database,$connection);
mysql_query("SET NAMES UTF8");

$sql = 'SELECT * FROM tbl_appointment LIMIT 20';
$rs_appointment = mysql_query($sql);

while($row_appointment = mysql_fetch_array($rs_appointment)){
$appointment[$row_appointment['app_id']] ['app_customer'] = $row_appointment['app_customer'];
$appointment[$row_appointment['app_id']] ['app_register'] = $row_appointment['app_register'];
$appointment[$row_appointment['app_id']] ['app_check'] = $row_appointment['app_check'];
}

$smarty = new Smarty();
$smarty->assign('appointment', $appointment);
$smarty->display('test_2.tpl');
?>

- ไฟล์ test_2.tpl

<html>
<head>
<title>Test Smary</title>
</head>
<body>
<table>
{foreach from=$appointment key=k item=i}
<tr><td>{$k}</td><td>{$i.app_register}</td><td>{$i.app_customer}</td><td>{$i.app_check}</td></tr>
{/foreach}
</table>
</body>
</html>


เท่านี้ก็เป็นตัวอย่างเบื้องต้นสำหรับการนำข้อมูลจากฐานข้อมูลออกมาแสดงด้วย Smarty template ครับ !

ไม่มีความคิดเห็น:

แสดงความคิดเห็น