MySQL是一種非常流行的關(guān)系型數(shù)據(jù)庫管理系統(tǒng)。它可以被用來制作后臺(tái)服務(wù)器,用于存儲(chǔ)和管理數(shù)據(jù)。接下來我們將介紹如何在MySQL中創(chuàng)建數(shù)據(jù)庫和表。
//連接數(shù)據(jù)庫 $con = mysqli_connect("localhost","root","password"); //創(chuàng)建數(shù)據(jù)庫 $sql = "CREATE DATABASE mydatabase"; if (mysqli_query($con, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($con); } //選擇數(shù)據(jù)庫 mysqli_select_db($con, "mydatabase"); //創(chuàng)建表 $sql = "CREATE TABLE mytable ( 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($con, $sql)) { echo "Table created successfully"; } else { echo "Error creating table: " . mysqli_error($con); }
以上代碼創(chuàng)建了一個(gè)名為mydatabase的數(shù)據(jù)庫和名為mytable的表。該表包含一個(gè)自增長(zhǎng)的id主鍵和四個(gè)字段:firstname、lastname、email和reg_date。其中reg_date字段將自動(dòng)設(shè)置為當(dāng)前時(shí)間戳。
當(dāng)你需要向表中添加數(shù)據(jù)時(shí),可以使用INSERT INTO語句:
//向表中添加數(shù)據(jù) $sql = "INSERT INTO mytable (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if (mysqli_query($con, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "
" . mysqli_error($con); }
接下來我們將介紹如何使用SELECT語句從表中獲取數(shù)據(jù):
//從表中獲取數(shù)據(jù) $sql = "SELECT id, firstname, lastname FROM mytable"; $result = mysqli_query($con, $sql); if (mysqli_num_rows($result) >0) { // 輸出數(shù)據(jù) while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 results"; }
以上代碼將從mytable表中獲取id、firstname和lastname字段,并以輸出的方式顯示在頁面上。
總的來說,使用MySQL制作后臺(tái)服務(wù)器雖然需要一定的學(xué)習(xí)成本,但是它可以幫助您輕松地存儲(chǔ)和管理數(shù)據(jù),從而為您的應(yīng)用程序提供更加完整和穩(wěn)定的功能。