วันพฤหัสบดีที่ 6 กันยายน พ.ศ. 2555

jFrameMyFriend.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jFrameMyFriend.java
 *
 * Created on 20 ต.ค. 2554, 0:44:03
 */

package telephone;

import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Panyapol
 */
public class jFrameMyFriend extends javax.swing.JFrame {

    private Connection conn = MyConnect.getConnection();
    private DefaultTableModel modelFriend;

    /** Creates new form jFrameMyFriend */
    public jFrameMyFriend() {
        initComponents();

        modelFriend = (DefaultTableModel) tableFriend.getModel(); //ผูกข้อมูลใน DB เข้ากับ Table
    }

    //นำข้อมูลใน DB Table มาแสดงบนตารางของโปรแกรม
    public void bindData(){
        try{
           
            //Clear record
            int totalRow = tableFriend.getRowCount() - 1;
            while(totalRow > - 1){
                modelFriend.removeRow(totalRow);
                totalRow--;
            }

            //Add record
            String search = txtSearch.getText();
            String sql = ""
                    + "SELECT * FROM tb_friend"
                    + " WHERE "
                    + "     name LIKE ('%" + search + "%')"
                    + "     OR tel LIKE ('%" + search + "%')"
                    + "     OR email LIKE ('%" + search + "%')"
                    + "     OR job LIKE ('%" + search + "%')";
           
            ResultSet rs = conn.createStatement().executeQuery(sql);
            int row = 0;

            while (rs.next()){
                modelFriend.addRow(new Object[0]);
                modelFriend.setValueAt(rs.getInt("id"), row, 0);
                modelFriend.setValueAt(rs.getString("name"), row, 1);
                modelFriend.setValueAt(rs.getString("tel"), row, 2);
                modelFriend.setValueAt(rs.getString("email"), row, 3);
                modelFriend.setValueAt(rs.getString("job"), row, 4);
                row++;
            }
            tableFriend.setModel(modelFriend);

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                        
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        txtJob = new javax.swing.JTextField();
        txtTel = new javax.swing.JTextField();
        txtEmail = new javax.swing.JTextField();
        cmdSave = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableFriend = new javax.swing.JTable();
        cmdUpdate = new javax.swing.JButton();
        cmdDelete = new javax.swing.JButton();
        cmdClear = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtSearch = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Telephone by Panyapol v.1.0.1");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setText("ชื่อ");

        jLabel2.setText("อาชีพ");

        jLabel3.setText("เบอร์โทร");

        jLabel4.setText("อีเมล์");

        txtJob.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtJobActionPerformed(evt);
            }
        });

        cmdSave.setText("บันทึก");
        cmdSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdSaveActionPerformed(evt);
            }
        });

        tableFriend.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id", "ชื่อเพื่อน", "เบอร์โทร", "อีเมล์", "อาชีพ"
            }
        ));
        tableFriend.setRowHeight(25);
        tableFriend.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableFriendMouseClicked(evt);
            }
        });
        tableFriend.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tableFriendKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tableFriend);
        tableFriend.getColumnModel().getColumn(0).setPreferredWidth(50);
        tableFriend.getColumnModel().getColumn(1).setPreferredWidth(200);
        tableFriend.getColumnModel().getColumn(2).setPreferredWidth(100);
        tableFriend.getColumnModel().getColumn(3).setPreferredWidth(150);
        tableFriend.getColumnModel().getColumn(4).setPreferredWidth(150);

        cmdUpdate.setText("แก้ไข");
        cmdUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdUpdateActionPerformed(evt);
            }
        });

        cmdDelete.setText("ลบ");
        cmdDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdDeleteActionPerformed(evt);
            }
        });

        cmdClear.setText("เครียร์");
        cmdClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdClearActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("ค้นหาเพื่อนของเรา"));

        txtSearch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtSearchKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(117, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 897, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmdSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdUpdate)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdDelete)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdClear))
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtJob, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtTel, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtEmail, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)))
                        .addGap(50, 50, 50)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(63, 63, 63))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtJob, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2))
                                .addGap(11, 11, 11)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cmdSave)
                            .addComponent(cmdUpdate)
                            .addComponent(cmdDelete)
                            .addComponent(cmdClear)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                      

    private void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
        try{
            String sql = "INSERT INTO tb_friend (name, tel, email, job) VALUES (?, ?, ?, ?)";
            PreparedStatement pre = conn.prepareStatement(sql);
            pre.setString(1, txtName.getText());
            pre.setString(2, txtTel.getText());
            pre.setString(3, txtEmail.getText());
            pre.setString(4, txtJob.getText());

            if(pre.executeUpdate() != -1){
                JOptionPane.showMessageDialog(this, "บันทึกรายการแล้ว", "ผลการบันทึกรายการ", JOptionPane.INFORMATION_MESSAGE);
                bindData();
            }
       
        }
        catch (Exception e){
            e.printStackTrace();
        }


    }                                      

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                
        // TODO add your handling code here:
        bindData();
    }                                

    private void tableFriendMouseClicked(java.awt.event.MouseEvent evt) {                                        
        // TODO add your handling code here:
        int index = tableFriend.getSelectedRow();
        txtName.setText(tableFriend.getValueAt(index, 1).toString());
        txtTel.setText(tableFriend.getValueAt(index, 2).toString());
        txtEmail.setText(tableFriend.getValueAt(index, 3).toString());
        txtJob.setText(tableFriend.getValueAt(index, 4).toString());
    }                                      

    private void cmdUpdateActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        int index = tableFriend.getSelectedRow();

        if(index != -1){
            int pk = (Integer) tableFriend.getValueAt(index, 0);
            //หรือวิธีนี้   Integer.parseInt(tableFriend.getValueAt(index, 0).toString());
            String sql = ""
                    + " UPDATE tb_friend SET "
                    + "     name = ?,     "
                    + "     tel = ?,      "
                    + "     email = ?,    "
                    + "     job = ?       "
                    + " WHERE id = " + pk;
            try{
                PreparedStatement Pre = conn.prepareStatement(sql);
                Pre.setString(1, txtName.getText());
                Pre.setString(2, txtTel.getText());
                Pre.setString(3, txtEmail.getText());
                Pre.setString(4, txtJob.getText());

                if(Pre.executeUpdate() != -1){
                    JOptionPane.showMessageDialog(this, "บันทึกการแก้ไขแล้ว", "บันทึกรายการ", JOptionPane.INFORMATION_MESSAGE);
                    bindData();
                }
            }catch(Exception e){
                e.printStackTrace();
            }
           
        }
    }                                        

    private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        int index = tableFriend.getSelectedRow();

        if(index != -1){
            int pk = (Integer) tableFriend.getValueAt(index, 0); //แปลงจากอ๊อบเจ็กไปเป็นเลขจำนวนเต็ม
            String sql = "DELETE FROM tb_friend WHERE id = " + pk;

            try{
                if(conn.createStatement().executeUpdate(sql) != -1);
                JOptionPane.showMessageDialog(this, "ลบรายการแล้ว", "ลบรายการ", JOptionPane.INFORMATION_MESSAGE);
                //ลบแล้วให้เครียร์ TextBox
                txtName.setText("");
                txtTel.setText("");
                txtEmail.setText("");
                txtJob.setText("");
                //รีเฟรชเทเบิล
                bindData();
            }catch(Exception e){
                e.printStackTrace();
            }          
        }
    }                                        

    //แก้ไขข้อมูลที่ JTable ได้เลย
    private void tableFriendKeyReleased(java.awt.event.KeyEvent evt) {                                      
        // TODO add your handling code here:
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            //Update data
            try{
                int index = tableFriend.getSelectedRow();
                int pk = (Integer) tableFriend.getValueAt(index, 0);

                String sql = ""
                    + " UPDATE tb_friend SET "
                    + "     name = ?,     "
                    + "     tel = ?,      "
                    + "     email = ?,    "
                    + "     job = ?       "
                    + " WHERE id = " + pk;
                PreparedStatement Pre = conn.prepareStatement(sql);
                Pre.setObject(1, tableFriend.getValueAt(index, 1));
                Pre.setObject(2, tableFriend.getValueAt(index, 2));
                Pre.setObject(3, tableFriend.getValueAt(index, 3));
                Pre.setObject(4, tableFriend.getValueAt(index, 4));
                Pre.executeUpdate();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }                                      

    private void cmdClearActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        txtName.setText("");
        txtTel.setText("");
        txtEmail.setText("");
        txtJob.setText("");
        txtSearch.setText("");
        bindData(); //Refresh JTable
    }                                      

    private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {                                    
        // TODO add your handling code here:
        String searchText = txtSearch.getText();

        try{
            if(!searchText.isEmpty()){
                bindData();
            }
        }catch(Exception e){

        }
    }                                    

    private void txtJobActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                    

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new jFrameMyFriend().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton cmdClear;
    private javax.swing.JButton cmdDelete;
    private javax.swing.JButton cmdSave;
    private javax.swing.JButton cmdUpdate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tableFriend;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtJob;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtSearch;
    private javax.swing.JTextField txtTel;
    // End of variables declaration                  

}

MyConnect.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package telephone;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author acer
 */
public class MyConnect {
    public static Connection getConnection(){
        try{
        Class.forName(com.mysql.jdbc.Driver.class.getName());
        return DriverManager.getConnection("jdbc:mysql://localhost/db_telephone", "root", "root");
        }catch(Exception e){
           e.printStackTrace();
        }
        return null;
    }

}

Main.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package telephone;

import java.sql.Connection;
import javax.swing.UIManager;

/**
 *
 * @author acer
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        /*try{
        Connection c = MyConnect.getConnection();
        System.out.println("connect complete" + c.getCatalog()); //+ c.getCatalog() << คือให้แสดงชื่อฐานข้อมูลด้วย
        }catch (Exception e){
            e.printStackTrace();
        }*/

        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            new jFrameMyFriend().setVisible(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

วันพุธที่ 15 สิงหาคม พ.ศ. 2555

โค้ด index.php


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
body,td,th {
color: #00F;
}
    body {
background-color: #FFF;
}
    a {
font-family: Verdana, Geneva, sans-serif;
}
    a:link {
text-decoration: none;
}
a:visited {
text-decoration: none;
}
a:hover {
text-decoration: none;
}
a:active {
text-decoration: none;
}
    </style>
</head>
<body>
<div><h1>สมุดเยี่ยม</h1></div>
<form action="add_data.php" method="post">
<table>
<tr>
<td>รายละเอียด</td>
<td><textarea name="g_detail"></textarea></td>
</tr>
<tr>
<td>ชื่อ</td>
<td><input type="text" name="g_name" /></td>
</tr>
<tr>
<td>อีเมล์</td>
<td><input type="text" name="g_email" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit" /></td>
</tr>
</table>
</form>
<hr/>
<table>
<?php
include('connect_db.php');
$number = 0;
$rs = mysql_query("SELECT * FROM guestbook ORDER BY g_id DESC");
while($value = mysql_fetch_array($rs)){
$number++;
?>
<div>#<?php echo $number;?></div>
<div>
<span><?php echo $value['g_detail'];?></span>
</div>
<div>
<span><b>Name :</b> <?php echo $value['g_name'];?></span>
<span><b>Email :</b> <?php echo $value['g_email'];?></span>
<span><b>Created : </b> <?php echo $value['g_date']; ?></span>
<span><a href="report_delete.php?g_id=<?php echo $value['g_id'];?>">แจ้งลบ</a></span>
</div>
<hr/>
<?php } ?>
</table>
<table width="161" border="0">
 <tr>
   <td colspan="3"><a href="index_manage.php">ติดต่อผู้ดูแลระบบ อาจารย์ปรีชา ปรือปรัง</a></td>
     </tr>
    </table>
</body>
</html>

ผลการรันโปรแกรม


วันจันทร์ที่ 28 พฤษภาคม พ.ศ. 2555

บที่ 1 โปรแกรมแรก

เริ่มต้นการเขียนโปรแกรมภาษา php เบื้องต้น

<?...?>      = Tag ในคำสั่ง php

print      = แสดงคำพูดในเครื่องหมาย "..."; ไม่มีการคำนวนค่า เช่น print "...";

echo      = แสดงคำพูดและการคำนวนในเครื่องหมาย "...", x +,-,*,/ y; เช่น echo "...", x+ y;

\      = ไว้คั่นคำสั่ง "..." เพือแสดงเครื่องหมายเช่น echo , print "\"..."\ "; หรือ "\$";

\n      = ไว้ขึ้นบรรทัดใหม่ใน Source แต่ไม่แสดงผลบนบราวเซอร์ เช่น print , echo "\n";

#,//      = คำสั่งสำหรับห้ามทำการแสดงผลของคำสั่งวางไว้หน้าคำสั่ง echo , print เช่น #,// echo , print "...";
      หรือการใช้ /* เพื่อเริ่มต้น และ */ เพื่อถึงจุดที่กำหนดไว้ เช่น /*...*/

$... = "...";      = เป็นค่าแสดงตัวแปร เช่น $... = "...";  , การแสดงผลเช่น print , echo "... $...";
         (สามารถคำนวนผลได้ เช่น $... +1 หรือ ++ และ $... -1 หรือ $... --)

$a

  • = "...";   = เป็นตัวแปรไว้เก็บค่าหลายๆๆ ค่า
  • หมายถึง ลำดับของตัวแปร 1,2,3,... และสามารถนำมาคำนวนได้เช่น "a[0] + a[1] + a[2]";


%      = เป็นตัวแปรในการหารแต่เอาแค่เศษ เช่น echo $1 % $2; หรือ echo 100 % 250;

เงื่อนไข      =   >   มากกว่า
         <   น้อยกว่า
         >=   มากกว่าหรือเท่ากัน
         <=   น้อยกว่าหรือเท่ากัน
         ==   เท่ากัน
         !=   ไม่เท่ากัน

if      = เป็นคำสั่งที่ใช้ตรวจสอบว่าผลของการเปรียบเทียบว่าจริงหรือเท็จ อยู่ในรูปแบบ
      if ( การเปรียบเทียบเช่น x >,<,>=,<=,==,!= y )
      {
         ถ้าจริงให้โปรแกรมเขียนอยู่ในนี้
         โปรแกรม ....
         โปรแกรม ....
      }
         ถ้าไม่จริงให้โปรแกรมเขียนอยู่ในนี้
         โปรแกรม ....
         โปรแกรม ....

else      = เป็นคำสั่งที่จะใช้ร่วมกับ if แต่ใช้ตรงกันข้ามกันมีรูปแบบดังนี้
      
      if (การเปรียบเทียบ)
      {
         ถ้าจริงให้โปรแกรมเขียนอยู่ในนี้
         โปรแกรม ....
         โปรแกรม ....

      }
      else
      {
         ถ้าไม่จริงให้โปรแกรมเขียนอยู่ในนี้
         โปรแกรม ....
         โปรแกรม ....

      }
              
      และสามารถใช้ if และ else กับการเปรียบเทียบได้ เช่น กำหนด $weight = 50;
      if ($weight > 25)
      {
         print "คุณผอมไปนะ";
      }
      else
      {
         print "คุณอ้วนไป";
      }

and (&&)   = การใช้คำสั่ง if แบบมีช่วงโดยการใช้คำสั่ง and เช่น กำหนด   $score = 90;
   print "ได้เกรด $score
";

   if ( $score >= 80 && $score <= 100)
   {

      print "ได้เกรด A";
   }
   print "
จบการตัดเกรด";
      
#   คือมีคะแนนระหว่าง 80 ถึง 100 ถึงจะแสดงผล ได้เกรด A

   การเปรียบเทียบหลายค่าเช่น  กำหนด   $score = 53;
   print "ได้เกรด $score
";

   if ( $score >= 80 && $score <= 100) {

      print "ได้เกรด A";
   }
   if ( $score >= 70 && $score <= 79) {

      print "ได้เกรด B";
   }   
   if ( $score >= 60 && $score <= 69) {

      print "ได้เกรด C";
   }
   if ( $score < 60) {

      print "ได้เกรด <font color=red>F</font>";
   }
   print "
จบการตัดเกรด";

or (||)   = ตรวจสอบค่า $... ในช่องใดช่องหนึ่ง เช่น กำหนด   $user = adicia;   $pass = istrator;
   if ( $user =="" || $pass=="" ) {
      print "กรุณาอย่าให้เป็นช่องว่าง";
   }
   else {
      print "Username คือ $user
";
      print "Password คือ $pass
";
   }

for   = การใช้คำสั่งในการกระทำซ้ำไปซ้ำมา มี 3 คำสั่ง 1. for 2. while 3. do..while
   1. for มีรูปแบบดังนี้
      for ($for = x;$for < y;$for ++)  
#   x คือค่าเริ่มต้น y คือค่าสุดท้าย -1
      {
         print "...";
      }
   2. while
      $while = 1;
         while ( $while < y ) 
#   ถ้า $while น้อยกว่า y
      {
         print "$while = ...
";
         $while ++;
#   ถ้า ++ นำเพิ่มขึ้นเรื่อยๆ และถ้า -- จะลดค่าลงเรื่อยๆ
      }
   3. do...while
      $while = x;
      do
      {
         print "$while = ...
";
         $while --;
      }
      while ( $while > y );
      print "End";
#   กระทำ do เลยแล้วมาตรวจสอบ ค่า while

Function   = รูปแบบ
      function Name ( )
#   ชื่อของ function
      {

      }
      Name();

Parameter   = รูปแบบ
      function Name ( $parameter )
#   ชื่อของ function 
      {
         echo "Name = ",3.14 * $parament * $parament,"
";
      }
      Name( x );
#   x คือจำนวนตัวเลข
#   อาจจะใช้ if ช่วยตรวจสอบ
      function Name ( $parameter )
#   ชื่อของ function 
      {
         if ( $parameter >=0 )
         {
         echo "Name = ",3.14 * $parament * $parament,"
";   
         }
         else
         {
            echo "ค่าที่ใช้ต้องมีค่ามากกว่า <font color=red>0</font> นะครับ";
         }
      }
      Name( x );
#   สามารถใช้ Function ได้ในทุกสถานที่มีรูปแบบดังนี้
      <?
# Name ชื่อ      Name( x );
      ?>
#   หรือเรียก Function จากไพล์อื่นโดย
      <?
         require "ที่อยู่ของไพล์ function";
         Name ( x );
      ?>

บทที่ 18 การเข้าถึงข้อมูลใน array ด้วย for each


 class ForIn {
public static void main(String[] args) {
int [] i = {1,3,4,5,6,4,0,8,9};
for (int data : i){
System.out.println(data);
}
}
}



บทที่ 17 การใช้งาน array ที่ซ้อนกัน

การสร้าง Array ซ้อนกัน  แบบการประกาศตัวแปรพร้อมกับกำหนดค่า


เรามาเริ่มลุยกันเลยดีกว่า  นะครับ  ?



class ComlexArray {
public static void main (String[] args) {
// การสร้าง Array ซ้อนกัน แบบการประกาษตัวแปรพร้อมกับกำหนดค่า
int [][] a={
{1,2,3},
{4,5,6},
{7,8,9},
};
// การสร้าง Array ซ้อนกัน แบบการประกาศตัวแปรไว้ก่อนแล้วมากำหนดค่าภายหลัง
int [][] b=new int[2][2];
b[0] = new int [] {1,2,3};
b[1] = new int [] {4,5,6};
}
}


บททที่ 16 การใช้งานตัวแปร array



การใช้งานตัวแปร array
คือตัวแปรที่เก็บข้อมูลเป็นชุด และมี index เป็นตัวชี้ การประกาศตัวแปรแบบ Array ทำได้ดังนี้


Type[] variable name={ค่าเริ่มต้น};
เช่น
       int []a={10,20,30};


การสร้าง Array เเล้วเก็บค่าเลย   เรามาดูกันเลย ok



 class Array {
public static void main(String[] args) {
/* int i = 10;
int j = 20;
int k = 30;
*/
//หากว่าผมเขียนโปรแกรมเก็บตัวแแปร 1000 ตัว  ผมคงเขียนโปรแกรมไม่ไหวแน่
// เพราะฉนั้นจึงมี Array เพื่อช่วยในการแก้ปัญหา เรามารู้จัก การสร้าง Array กับการเก็บค่ากันดีกว่า
 
int[] i={10,20,30,40,50};  //การสร้าง Array แล้วเก็บค่าเลย
int[] j=new int[5]; //การสร้าง Array มารอเก็บค่า
 
// ต่อไปมาดูการสร้าง Array 2 มิติ
 
int [][] k=new int[2][2];
k[0][0]=1;
k[1][0]=2;
k[1][1]=3;
k[0][1]=4;  
 
}
}

บทที่ 15 การทำซ้ำด้วย do while


 class Do {
public static void main (String[] args) {
int x = 0;
 
do {
System.out.println(x);
x++;
}while (x>=5);  
//  ขออธิบายนิดนึงนะครับเกี่ยวกับ loop do while
//  การทำงานของ loop do while ถ้าหากว่าเงื่อนไขที่เราตั้งเป็นจริงมันก็จะทำงาน
//  เเต่ถ้าเงื่อนไขไม่เป็นจริงมันก็จะทำงานในรอบที่ 1 ก่อนเสมอ
// จากตัวอย่างแน่นอนว่า เราตั้งให้ (x<=5) ซึ้งเป็นจริงก็จะ print 0,1,2,3,4,5
// แต่หากว่าเราตั้ง เงื่อนไขไหม เช่น (x>=5) ซึ่งแน่นอนผลลัพธ์ของเราก็คือ '0'
}
}


บทที่ 14 การทำซ้ำด้วย while


class While {
public static void main (String[] args) {
int x = 0;
while (x<=20) {
System.out.println(x);
x++;

}
}
}