// connect to mysql database $conn = newmysqli($host, $user, $password, $db); if ($conn->connect_error) { // connection error die($conn->connect_error); }
建表
$sql = "CREATE TABLE IF NOT EXISTS tablename ( ID INT AUTO_INCREMENT PRIMARY KEY, Name varchar(100) NOT NULL, RefID int, FOREIGN KEY (RefID) REFERENCES Ref (ID) )";
$stmt = $conn->prepare("insert into table (email, date) VALUE (?,?)"); $stmt->bind_param("ss", $_SESSION['user'], $_POST['date']); if (!$stmt->execute()) { die($conn->error); } else { echo"inserted, id is " . $stmt->insert_id; }
更新
$query = $conn->prepare("update User set profile = ?, photo = ? where id = ?"); $query->bind_param('ssi', $_POST['profile'], $photo, $_SESSION['user'][0]); $query->execute();
查询 (单条)
$query = $conn->prepare("SELECT * FROM user where email=? and password=?"); $query->bind_param('ss', $email, $password); $query->execute(); $result = $query->get_result(); $user = $result->fetch_array(MYSQLI_NUM); // user 是数组, // 字段从 0 开始排列,没有 named key
查询 (多条)
$query = $conn->prepare("SELECT * from meal where email=?"); $query->bind_param('s', $_SESSION["email"]); $query->execute(); $result = $query->get_result()->fetch_all();
// result 是数组,每个元素也是数组。 // 字段从 0 开始排列,没有 named key
删除
$query = $conn->prepare("delete from Likes where photoId = ? and userId = ?"); $query->bind_param('ii', $_GET['id'], $_SESSION['user'][0]); $query->execute();
$query = "UPDATE post SET title = :title, content = :content WHERE id = :id"; $statement = $db->prepare($query); $statement->bindValue(':title', $title); $statement->bindValue(':content', $content); $statement->bindValue(':id', $id); $statement->execute(); $insert_id = $db->lastInsertId();
查询
$query = "SELECT * FROM post ORDER BY creation_time DESC LIMIT 5"; $statement = $db->prepare($query); $statement->execute(); $posts= $statement->fetchAll();
删除
$query = "DELETE FROM post WHERE id = :id"; $statement = $db->prepare($query); $statement->bindValue(':id', $id, PDO::PARAM_STR); $statement->execute();
授权
登录
// select user from db first session_start(); $_SESSION['user'] = $user; header("Location: index.php"); die();