สวัสดีครับสำหรับใครที่ต้องทำโปรแกรม หรือเว็บไซต์ด้วย PHP (ที่จริงจะใช้ ASP.NET , JSP หรืออื่นๆ ก็ได้นะ) แล้วต้องใช้งานร่วมกับ ฐานข้อมูล MySQL หนึ่งในพื้นฐานที่สำคัญ ก็คือการ เพิ่มข้อมูลลงฐานข้อมูล เอาล่ะครับมาดูกันดีกว่า ว่าถ้าเราต้องการเพิ่มข้อมูลลงในตาราง จะต้องใช้ Query หรือ SQL แบบไหนครับ ^^ Show คำสั่ง SQL ในการเพิ่มข้อมูล รูปแบบที่ 1 : ไม่กำหนดชื่อฟิลด์
รูปแบบที่ 2 : กำหนดชื่อฟิลด์
ตัวอย่างการใช้งาน ตัวอย่างที่ 1 ต้องการเพิ่มข้อมูลของพนักงาน รหัส a0001 นาย โชคดี มีชัย อายุ 28 ปี เพศชาย ลงในตารางชื่อ employee
ตัวอย่างที่ 2 ต้องการเพิ่มข้อมูลของพนักงาน รหัส a0001 นาย โชคดี มีชัย อายุ 28 ปี เพศชาย ลงในตารางชื่อ employee
เป็นยังไงบ้างครับ ไม่ยากเลย ลองนำไปใช้ดูนะครับ จะใช้ใน Tool PHPMYADMIN ลองทดสอบดูก็ได้นะครับ จำและหัดนำไปใช้ให้คล่องนะครับ เพราะเราต้องนำ SQL นี้ ไปเขียนในโปรแกรมหรือเว็บไซต์ ของเรานั่นเองครับ ^^ Insert Data Into MySQL Using MySQLi and PDOAfter a database and a table have been created, we can start adding data in them. Here are some syntax rules to follow:
The INSERT INTO statement is used to add new records to a MySQL table: INSERT
INTO table_name (column1, column2, column3,...) To learn more about SQL, please visit our SQL tutorial. In the previous chapter we created an empty table named "MyGuests" with five columns: "id", "firstname", "lastname", "email" and "reg_date". Now, let us fill the table with data. Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default update of current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value. The following examples add a new record to the "MyGuests" table: Example (MySQLi Object-oriented)<?php // Create connection $sql = "INSERT INTO MyGuests (firstname, lastname, email) if ($conn->query($sql) === TRUE) { $conn->close(); Example (MySQLi Procedural)<?php // Create connection $sql = "INSERT INTO MyGuests (firstname, lastname, email) if (mysqli_query($conn, $sql)) { mysqli_close($conn); Example (PDO)<?php try { $conn
= null; |