MySQL數據庫儲存是一種常見的數據存儲方式,如何調用數據庫中的數據也是每個開發人員必須掌握的技能之一。
首先,我們需要使用MySQL提供的API連接到數據庫。在PHP中,我們可以使用mysqli或PDO兩種方式,如下:
//使用mysqli方式連接數據庫 $mysqli = new mysqli("localhost", "username", "password", "dbname"); if ($mysqli ->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli ->connect_error; exit(); } //使用PDO方式連接數據庫 $dsn = "mysql:host=localhost;dbname=dbname"; $username = "username"; $password = "password"; try { $pdo = new PDO($dsn, $username, $password); } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); exit(); }
連接成功后,我們可以使用SQL語句查詢或操作數據庫中的數據。以下是一些常見的SQL操作:
//查詢數據 $sql = "SELECT * FROM `table`"; $result = $mysqli ->query($sql); while($row = $result ->fetch_assoc()) { echo $row["column"]; } $sql = "SELECT * FROM `table`"; $stmt = $pdo->query($sql); while ($row = $stmt->fetch()) { echo $row["column"]; } //插入數據 $sql = "INSERT INTO `table` (`column1`, `column2`) VALUES ('value1', 'value2')"; $mysqli ->query($sql); $sql = "INSERT INTO `table` (`column1`, `column2`) VALUES (?, ?)"; $stmt = $pdo->prepare($sql); $stmt->execute(['value1', 'value2']); //更新數據 $sql = "UPDATE `table` SET `column`='value' WHERE `id`='1'"; $mysqli ->query($sql); $sql = "UPDATE `table` SET `column`=? WHERE `id`=?"; $stmt = $pdo->prepare($sql); $stmt->execute(['value', 1]); //刪除數據 $sql = "DELETE FROM `table` WHERE `id`='1'"; $mysqli ->query($sql); $sql = "DELETE FROM `table` WHERE `id`=?"; $stmt = $pdo->prepare($sql); $stmt->execute([1]);
以上是MySQL數據庫儲存的基本操作,開發者們可以根據自己的需求進行靈活應用。
上一篇css局部加粗字體
下一篇css層疊樣式表優先級