ฟังก์ชัน query ของ mysqli ถ้าใช้กับ Create, Insert, Update, Delete แล้วสำเร็จจะ retrun true
และถ้าจะเอา id ของข้อมูลที่ใส่เข้าไปใหม่ของ table ที่ AUTO_INCREMENT PRIMARY
KEY
ให้ใช้ $last_id =
$conn->insert_id;
Create Database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo
"Error creating database: " . $conn->error;
}
Create Table
$sql
= "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY
KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email
VARCHAR(50),
reg_date TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table
MyGuests created successfully";
} else {
echo
"Error creating table: " . $conn->error;
}
Insert
$sql = "INSERT INTO
MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
$last_id =
$conn->insert_id;
echo "New record created successfully. Last
inserted ID is: " . $last_id;
} else {
echo
"Error: " . $sql . "<br>" . $conn->error;
}
Insert Multiple
$sql = "INSERT INTO
MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO
MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO
MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";
if ($conn->multi_query($sql) === TRUE) {
echo "New
records created successfully";
} else {
echo
"Error: " . $sql . "<br>" . $conn->error;
}
Update
$sql
= "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record
updated successfully";
} else {
echo
"Error updating record: " . $conn->error;
}
Delete
$sql
= "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record
deleted successfully";
} else {
echo
"Error deleting record: " . $conn->error;
}
ไม่มีความคิดเห็น:
แสดงความคิดเห็น