如何使用PHP 將影像儲存到資料庫
問題陳述
問題陳述問題陳述
SQL 注入漏洞: 該程式碼容易受到 SQL 注入的攻擊,這可能會危害資料庫完整性。
不正確的SQL 查詢:
INSERT 語句對字串值使用單引號('),而不是雙引號(")。使用 PDO 的程式碼範例
PHP代碼:
<?php try { // Connect to the database using PDO $dsn = 'mysql:host=localhost;dbname=database_name'; $username = 'username'; $password = 'password'; $conn = new PDO($dsn, $username, $password); // Check if the image column is BLOB type $query = "DESCRIBE table_name"; $stmt = $conn->prepare($query); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); if ($result[0]['Type'] != 'blob') { throw new Exception('The image column is not of BLOB type'); } // Process the image upload $file = $_FILES['image']['tmp_name']; $image_name = $_FILES['image']['name']; $image = file_get_contents($file); // Prepare the INSERT statement $query = "INSERT INTO product_images (id, image_name, image) VALUES (1, ?, ?)"; $stmt = $conn->prepare($query); // Execute the statement and bind parameters $stmt->execute([$image_name, $image]); // Success message echo "Image uploaded successfully"; } catch (Exception $e) { echo "Failed to upload image: " . $e->getMessage(); } ?>
HTML表單
<form action="insert_product.php" method="POST" enctype="multipart/form-data"> <label for="image">File:</label> <input type="file" name="image">
注意事項
以上是使用 PHP 將映像儲存到 MySQL 資料庫時如何解決 SQL 語法錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!