PHP 與 MySQL 的互動:新增資料
<?php
require_once 'conn.php';
$username = 'apple';
$result = $conn->query("insert into users(username) value('" . $username . "')");
// 也可以 $result = $conn->query("insert into users(username) value('apple')")
// 要注意外面已經用雙引號,所以裡面無法再用雙引號要用單引號
if (!$result) {
die($conn->error);
}
print_r($result);
結果印出 1 就是成功,去資料庫也看到有新增一筆 apple
可以把 query() 裡面的東西再用一個變數存起來,$sql="insert into users(username) value('".$username."')";
或是可以用 Huli 更推薦的方法,使用 php 的一個函式叫做 sprintf
第一個參數是字串,動態塞進去的變成 %s
第二個放你的變數
那他就會把第二個參數帶到 %s
$sql = sprintf("insert into users(username) value('%s')", $username);
<?php
require_once 'conn.php';
if (empty($_POST['username'])) {
die('請輸入 username');
}
$username = $_POST['username'];
$sql = sprintf("INSERT INTO users(username) VALUE('%s') ORDER BY id ASC", $username );
// ASC 由小到大,DESC 由大到小
echo 'SQL:' . $sql . "<br>";
$result = $conn->query($sql);
if (!$result) {
die($conn->error);
}
echo "新增成功";
header("Location: index.php");
去 phpMyAdmin 把 username 這個欄位設成獨一
那輸入重複的 value 就會出現 Duplicate entry 'ccc' for key 'username'
這個錯誤
也可以打開 DevTools ,記得要把 Preserve log 打勾,有勾的話中間頁面跳轉的 log 也會記住
PHP 與 MySQL 的互動:刪除資料
原本的 index.php 檔 增加 echo sprintf("<a href='delete.php?id=%d'>刪除</a><br>", $row['id']);
刪除就用 GET 拿資料
$conn->affected_rows; 可以看出影響幾列
<?php
require_once 'conn.php';
$result = mysqli_query($conn, "SELECT * FROM users");
if (!$result) {
die($conn->error);
}
// 拿資料,可以把他想成物件
while ($row = $result->fetch_assoc()) {
echo "id:" . $row['id'];
echo sprintf("<a href='delete.php?id=%d'>刪除</a><br>", $row['id']);
echo "username:" . $row['username'] . '<br><br>';
}
?>
<form method="POST" action="add.php">
username: <input name="username" />
<input type="submit" />
</form>
delete.php
<?php
require_once 'conn.php';
if (empty($_GET['id'])) {
die('請輸入 id');
}
$id = $_GET['id'];
$sql = sprintf("DELETE from users WHERE id = %d", $id);
echo 'SQL:' . $sql . "<br>";
$result = $conn->query($sql);
if (!$result) {
die($conn->error);
}
if ($conn->affected_rows >= 1) {
echo '刪除成功';
} else {
echo '查無資料';
}
// header("Location: index.php");
PHP 與 MySQL 的互動:編輯資料
<?php
require_once('conn.php');
if (empty($_POST['id']) || empty($_POST['username'])) {
die('請輸入 id 與 username');
}
$id = $_POST['id'];
$username = $_POST['username'];
$sql = sprintf(
"update users set username='%s' where id=%d",
$username,
$id
);
echo $sql . '<br>';
$result = $conn->query($sql);
if (!$result) {
die($conn->error);
}
header("Location: index.php");
?>