MySQL是一種關(guān)系型數(shù)據(jù)庫(kù)管理系統(tǒng),廣泛應(yīng)用于現(xiàn)代web應(yīng)用程序的開(kāi)發(fā)和維護(hù)。在本文中,我們將介紹一些MySQL數(shù)據(jù)庫(kù)的存取方法。
1. 連接到MySQL
$host = "localhost"; $username = "username"; $password = "password"; $dbname = "databasename"; $conn = mysqli_connect($host, $username, $password, $dbname); if(!$conn) { die("Connection failed: " . mysqli_connect_error()); }
2. 創(chuàng)建表
$sql = "CREATE TABLE users ( 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(mysqli_query($conn, $sql)) { echo "Table created successfully"; } else { echo "Error creating table: " . mysqli_error($conn); }
3. 插入數(shù)據(jù)
$sql = "INSERT INTO users (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if(mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "
" . mysqli_error($conn); }
4. 查詢數(shù)據(jù)
$sql = "SELECT id, firstname, lastname FROM users"; $result = mysqli_query($conn, $sql); if(mysqli_num_rows($result) >0) { while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 results"; }
5. 更新數(shù)據(jù)
$sql = "UPDATE users SET lastname='Doe' WHERE id=1"; if(mysqli_query($conn, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($conn); }
6. 刪除數(shù)據(jù)
$sql = "DELETE FROM users WHERE id=1"; if(mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); }
以上就是一個(gè)基本的MySQL存取方法的介紹。當(dāng)然,MySQL還有更多強(qiáng)大的功能和數(shù)據(jù)類型,讀者可以深入學(xué)習(xí)和研究。