MySQL是一種廣泛使用的關系型數據庫管理系統,很多人都想掌握這個技能。下面是一份MySQL教學腳本,將幫助你入門。
// 連接數據庫 $servername = "localhost"; $username = "username"; $password = "password"; // 創建連接 $conn = new mysqli($servername, $username, $password); // 檢查連接是否成功 if ($conn->connect_error) { die("連接失敗: " . $conn->connect_error); } echo "連接成功"; // 創建數據庫 $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "數據庫創建成功"; } else { echo "Error creating database: " . $conn->error; } // 創建表 $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 DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; if ($conn->query($sql) === TRUE) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: " . $conn->error; } // 添加數據 $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { $last_id = $conn->insert_id; echo "新記錄插入成功,ID為: " . $last_id; } else { echo "Error: " . $sql . "
" . $conn->error; } // 查詢數據 $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows >0) { // 輸出數據 while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 結果"; } // 關閉連接 $conn->close();
通過學習以上腳本,你將學到如何創建數據庫、創建表、添加數據和查詢數據等基本操作。希望這份MySQL教學腳本能夠幫助到你入門學習。
上一篇MYSQL教程 56
下一篇css怎么顯示圓形