รูปแบบไม่มีอะไรมาก
เริ่มต้น สร้างไฟล์ connect.php สำหรับใช้ในการเชิ่อมต่อฐานข้อมูล mysql
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php // connect.php $db_config = array ( "host" => "localhost" , // กำหนด host "user" => "root" , // กำหนดชื่อ user "pass" => "" , // กำหนดรหัสผ่าน "dbname" => "test" , // กำหนดชื่อฐานข้อมูล "charset" => "utf8" // กำหนด charset ); $mysqli = @ new mysqli( $db_config [ "host" ], $db_config [ "user" ], $db_config [ "pass" ], $db_config [ "dbname" ]); if (mysqli_connect_error()) { die ( 'Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); exit ; } if (! $mysqli ->set_charset( $db_config [ "charset" ])) { // เปลี่ยน charset เป้น utf8 พร้อมตรวจสอบการเปลี่ยน // printf("Error loading character set utf8: %sn", $mysqli->error); // ถ้าเปลี่ยนไม่ได้ } else { // printf("Current character set: %sn", $mysqli->character_set_name()); // ถ้าเปลี่ยนได้ } //echo $mysqli->character_set_name(); // แสดง charset เอา comment ออก //echo 'Success... ' . $mysqli->host_info . "n"; //$mysqli->close(); ?> |
ตัวอย่างการใช้งาน
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <?php include ( "connect.php" ); ?> <!DOCTYPE html> <html lang= "en" > <head> <meta charset= "UTF-8" > <link rel= "stylesheet" type= "text/css" href= "bootstrap/css/bootstrap.min.css" /> <title>Test mysqli 1</title> </head> <body> <div class = "container" > <br> <table class = "table" > <tr> <th>#</th> <th>Province</th> </tr> <?php $i =1; $q =" SELECT * FROM province_th LIMIT 30 "; $result = $mysqli ->query( $q ); // ทำการ query คำสั่ง sql $total = $result ->num_rows; // นับจำนวนถวที่แสดง ทั้งหมด while ( $rs = $result ->fetch_object()){ // วนลูปแสดงข้อมูล ?> <tr> <td><?= $i ?></td> <td><?= $rs ->province_name?></td> </tr> <?php $i ++; } ?> </table> </div> <?php $mysqli ->close(); ?> </body> </html> |
มาดูคำสั่งที่ใช้บ่อย
$result = $mysqli->query($q) ทำการ query คำสั่ง sql
$total=$result->num_rows; หาจำนวนแถวที่แสดงทั้งหมด
$mysqli->close(); ปิดการเชิ่อมต่อ server database mysql
การวนลูปแสดงข้อมูล มีให้เลือก 4 แบบ
$result->fetch_assoc() ส่งค่ากลับมาแบบ array key เป็นชื่อ field
$result->fetch_row() ส่งค่ากลับมาแบบ array key เป็น index เริ่มที่ 0,1 ....
$result->fetch_array() ส่งค่าทั้งแบบ assoc และ row เขาว่าไม่น่าใช้ กินแรม
$result->fetch_object() ส่งค่ากลับมาแบบ object
เราจะใช้ตัวนี้เป็นหลัก เหตุผล
เพราะเวลา เรียกใช้งาน ไม่ต้องใส่เครื่องหมาย " " เช่น $rs->province_name;
ถ้าใช้แบบ array หรือ assoc เราอาจจะต้องพิมพ์ $rs["province_name'] ส่วนใครจะ
ถนัดแบบไหนเลือกได้