MySQL是一款非常流行的關系型數據庫管理系統,它的使用十分廣泛,特別是在Web開發中。在進行MySQL操作時,我們需要使用一些代碼來實現我們的目標。下面是一些常見的MySQL操作代碼。
//連接數據庫 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; //創建連接 $conn = new mysqli($servername, $username, $password, $dbname); //檢查連接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //創建數據庫 $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $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 results"; } //插入數據 $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "
" . $conn->error; } //更新數據 $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; } //刪除數據 $sql = "DELETE FROM MyGuests WHERE id=3"; if ($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; } //關閉連接 $conn->close();
以上是一些常見的MySQL操作代碼。這些代碼可以幫助開發者快速實現一些常用的數據庫操作。當然,數據庫操作需要謹慎處理,應避免出現數據丟失或者泄露的情況。
上一篇css怎么設二級菜單
下一篇css怎么設置div水平