:::

5-2 用AI來產生表單儲存功能

一、請AI來產生寫入語法

  1. 請輸入以下提示詞:
    請根據以下SQL語法來產生PHP8名為store()的函數:
    其值來源為POST,表單欄位名稱和資料欄位名稱一致
    PDO物件已建立,global引入使用即可
    存入時用 ? 佔位符的方式處理,最後取得存入的 id 值。
    
    接著根據 id 值建立 uploads/id/ 文章檔案目錄來存放圖檔
    完成多個檔案上傳至文章檔案目錄的功能,
    請將原圖縮小到指定寬度,並命為 main_新檔名
    並同時也產生一張更小的縮圖,並命為 thumb_新檔名
    縮圖請另外建立函數處理,以方便分別指定寬度
    最後,以圖檔路徑為索引,縮圖路徑為值,存為 json 格式。
    並更新該文章的 media 欄位值
    
    CREATE TABLE `school_news` (
      `id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '編號',
      `news_title` VARCHAR(255) NOT NULL COMMENT '新聞標題',
      `news_content` TEXT NOT NULL COMMENT '新聞內容',
      `related_link` VARCHAR(255) COMMENT '相關連結',
      `publisher` VARCHAR(100) NOT NULL COMMENT '發布者',
      `school_name` VARCHAR(100) NOT NULL COMMENT '學校名稱',
      `report_date` DATE NOT NULL COMMENT '報導日期',
      `upload_type` ENUM('image', 'youtube') NOT NULL COMMENT '上傳種類',
      `youtube_url` VARCHAR(255) COMMENT 'Youtube影片網址',
      `media` JSON COMMENT '多檔案JSON資訊',
      `views` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '點閱數',
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    
  2. 會產生如下結果,包含儲存到資料庫和縮圖的函數:

    <?php
    
    function resizeImage(string $sourcePath, string $destPath, int $targetWidth): bool
    {
        list($width, $height) = getimagesize($sourcePath);
        $ratio = $targetWidth / $width;
        $targetHeight = intval($height * $ratio);
    
        $sourceImage = imagecreatefromstring(file_get_contents($sourcePath));
        $destImage = imagecreatetruecolor($targetWidth, $targetHeight);
    
        imagecopyresampled($destImage, $sourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
    
        $result = imagejpeg($destImage, $destPath, 90);
    
        imagedestroy($sourceImage);
        imagedestroy($destImage);
    
        return $result;
    }
    
    function store(): int
    {
        global $pdo;
    
        try {
            $sql = "INSERT INTO school_news (news_title, news_content, related_link, publisher, school_name, report_date, upload_type, youtube_url) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $pdo->prepare($sql);
            
            $stmt->execute([
                $_POST['news_title'],
                $_POST['news_content'],
                $_POST['related_link'] ?? null,
                $_POST['publisher'],
                $_POST['school_name'],
                $_POST['report_date'],
                $_POST['upload_type'],
                $_POST['youtube_url'] ?? null
            ]);
            
            $id = $pdo->lastInsertId();
            
            $uploadDir = "uploads/{$id}/";
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $mediaJson = [];
            
            if ($_POST['upload_type'] === 'image' && !empty($_FILES['image_files']['name'])) {
                foreach ($_FILES['image_files']['name'] as $key => $name) {
                    $tmpName = $_FILES['image_files']['tmp_name'][$key];
                    if ($_FILES['image_files']['error'][$key] === UPLOAD_ERR_OK) {
                        $extension = pathinfo($name, PATHINFO_EXTENSION);
                        $newName = uniqid() . '.' . $extension;
                        $destination = $uploadDir . $newName;
                        
                        // 移動上傳的文件
                        move_uploaded_file($tmpName, $destination);
                        
                        // 創建主圖(寬度800px)
                        $mainImage = $uploadDir . 'main_' . $newName;
                        resizeImage($destination, $mainImage, 800);
                        
                        // 創建縮略圖(寬度200px)
                        $thumbImage = $uploadDir . 'thumb_' . $newName;
                        resizeImage($destination, $thumbImage, 200);
                        
                        // 刪除原始上傳的文件
                        unlink($destination);
                        
                        $mediaJson[$mainImage] = $thumbImage;
                    }
                }
            }
            
            if (!empty($mediaJson)) {
                $updateSql = "UPDATE school_news SET media = ? WHERE id = ?";
                $updateStmt = $pdo->prepare($updateSql);
                $updateStmt->execute([json_encode($mediaJson), $id]);
            }
            
            return $id;
        } catch (PDOException $e) {
            error_log("Database Error: " . $e->getMessage());
            throw new Exception("資料儲存失敗,請稍後再試。");
        } catch (Exception $e) {
            error_log("Error: " . $e->getMessage());
            throw new Exception("發生未知錯誤,請聯繫管理員。");
        }
    }
    
    // 使用示例
    try {
        $newId = store();
        echo "新聞已成功保存,ID: " . $newId;
    } catch (Exception $e) {
        echo "錯誤: " . $e->getMessage();
    }
    

    基本上已經差不多相當完整,我們稍加調整即可。


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D2013%26tbsn%3D55

計數器

今天: 3219321932193219
昨天: 2259225922592259
總計: 7952017795201779520177952017795201779520177952017