MySQL是一種廣泛使用的關(guān)系型數(shù)據(jù)庫管理系統(tǒng),很多人都想掌握這個(gè)技能。下面是一份MySQL教學(xué)腳本,將幫助你入門。
// 連接數(shù)據(jù)庫 $servername = "localhost"; $username = "username"; $password = "password"; // 創(chuàng)建連接 $conn = new mysqli($servername, $username, $password); // 檢查連接是否成功 if ($conn->connect_error) { die("連接失敗: " . $conn->connect_error); } echo "連接成功"; // 創(chuàng)建數(shù)據(jù)庫 $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "數(shù)據(jù)庫創(chuàng)建成功"; } else { echo "Error creating database: " . $conn->error; } // 創(chuàng)建表 $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; } // 添加數(shù)據(jù) $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; } // 查詢數(shù)據(jù) $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows >0) { // 輸出數(shù)據(jù) while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 結(jié)果"; } // 關(guān)閉連接 $conn->close();
通過學(xué)習(xí)以上腳本,你將學(xué)到如何創(chuàng)建數(shù)據(jù)庫、創(chuàng)建表、添加數(shù)據(jù)和查詢數(shù)據(jù)等基本操作。希望這份MySQL教學(xué)腳本能夠幫助到你入門學(xué)習(xí)。
上一篇MYSQL教程 56
下一篇css怎么顯示圓形