สร้างแบบฟอร์มสำหรับบันทึกค่า ตามโครงสร้างตาราง book ด้วยคำสั่ง SHOW FULL COLUMNS

โดย CyberMAN •

PHP MySQLi and MySQL table structure

กำหนดให้ในฐานข้อมูลชื่อ test มีตาราง book ที่มีโครงสร้างตามรูป

เราสามารถเขียนโปรแกรม PHP  เพื่ออ่านค่าโครงสร้างของตาราง book ใน MySQL ได้โดยใช้คำสั่ง SHOW FULL COLUMNS ของ SQL ดังนี้

<?php
$table = 'book';
$mysqli = new mysqli("localhost", "dev", "dev.1234", "test");
/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
}
/* Create table doesn't return a resultset */
if ($result = $mysqli->query("SHOW FULL COLUMNS FROM $table ")) {
       /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        $data[] = array(
                    'name' => $row['Field'],
                    'type' => $row['Type'],
                    'comment' => $row['Comment']
                );
    }

    $result->free();
}
$mysqli->close();
?>
<html>
 <head>
  <meta charset="UTF-8">
</head>
<body>
<h2>สร้างแบบฟอร์มบันทึกค่า ตามโครงสร้างตาราง "<?php echo $table;?>"</h2>
<table>
<?php
    $tbody = '';
    foreach($data as $key=>$arr){
        $label = ($arr['comment'] != '') ?  $arr['comment'] : $arr['name'];
        $tbody .= '<tr>'
                . '<td align="right"><b>' . $label . ' : </b></td>'
                . '<td><input type="" name="'. $arr['name'] .'" /></td>'
                . '</tr>';
    }

    echo $tbody;
?>
</table>
</body>
</html>



ผลลัพธ์ที่ได้จะวนลูปแสดงคอลัมน์เพื่อสร้าง INPUT ตามโครงสร้างตาราง book


สังเกตุว่าถ้าฟิลด์ไหนที่มีการระบุ Comment เอาไว้จะดึงคอมเมนต์มาใช้งาน
$label = ($arr['comment'] != '') ? $arr['comment'] : $arr['name'];

แต่ถ้า Comment เป็นค่าว่าง ก็จะเอาชื่อฟิลด์ $arr['name'] มาแสดงด้านหน้า ดังในรูปด้านบน



สำหรับโครงสร้าง book สร้างด้วยคำสั่งดังต่อไปนี้

โค้ด SQL สำหรับสร้างตารางทดสอบ


 CREATE TABLE IF NOT EXISTS `book` (
  `bk_id` int(11) NOT NULL AUTO_INCREMENT,
  `bk_month` varchar(2) NOT NULL COMMENT 'เดือน',
  `bk_code` varchar(20) NOT NULL COMMENT 'รหัส',
  `bk_name` varchar(100) NOT NULL COMMENT 'ชื่อ',
  `bk_last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`bk_id`,`bk_month`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `book`
--
INSERT INTO `book` (`bk_id`, `bk_month`, `bk_code`, `bk_name`, `bk_last_update`) VALUES
(1, '01', '59012', 'ใจ', '2017-11-06 07:09:15'),
(2, '02', '60123', 'จริง', '2017-11-06 07:09:08'),
(5, '01', '59627', 'จน', '2017-11-06 07:09:32'),
(3, '03', '60456', 'จะ', '2017-11-06 07:09:22'),
(4, '01', '61024', 'จร', '2017-11-06 07:09:42');



PHP CI MANIA - PHP Code Generator 
โปรแกรมช่วยสร้างโค้ด ลดเวลาการเขียนโปรแกรม เขียนโปรแกรมง่ายและสะดวกขึ้น
สนใจสั่งซื้อราคาสุดคุ้ม >> http://fastcoding.phpcodemania.com/