我在让PHP将图像路径或目录插入MySQL数据库时遇到问题。它只存储图像名称,而不是图像的路径和名称。此外,我正在重命名图像以匹配它存储在其下的项目的标题(例如,蓝色汽车 - 标题,蓝色汽车 - 图像名称)。它不是上传新的图像名称,而是仅存储原始图像名称。
这是我重命名和上传图片等的代码:
// The directory that will recieve the uploaded file
$dir = 'uploads/';
//variables for images
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["picture"]["name"]);
$extension = end($temp);
if(isset($_POST['submit'])) {
if (strlen($title)>0 && strlen($description)>0) {
move_uploaded_file($_FILES['picture']['tmp_name'], $dir . "/" . $title ."." . $extension);
// Query database and insert data into item table
$itemQry = 'INSERT INTO items (title, picture, startPrice, category, description, quantity, location, sellingFormat, duration, paymentType, postageDetails)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
$statement = $conn->prepare($itemQry);
$statement->bind_param('sssssssssss', $title, $_FILES['picture']['name'], $startPrice, $category, $description, $quantity, $location, $sellingFormat, $duration, $paymentType, $postageDetails);
$statement->execute();
答案 0 :(得分:0)
试试这个:
// The directory that will recieve the uploaded file
$dir = 'uploads/';
//variables for images
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["picture"]["name"]);
$extension = end($temp);
if(isset($_POST['submit'])) {
if ((strlen($title) > 0) && (strlen($description) > 0)) {
$newFilePath = $dir . "/" . $title . "." . $extension;
move_uploaded_file($_FILES['picture']['tmp_name'], $newFilePath);
// Query database and insert data into item table
$itemQry = 'INSERT INTO items
(title, picture, startPrice, category, description,
quantity, location, sellingFormat, duration,
paymentType, postageDetails)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
$statement = $conn->prepare($itemQry);
$statement->bind_param('sssssssssss', $title, $newFilePath,
$startPrice, $category, $description,
$quantity, $location, $sellingFormat,
$duration, $paymentType, $postageDetails);
$statement->execute();
}
}
注意:这里我使用$newFilePath
作为新变量,它保留路径和新文件名,并使用相同的方法插入到DB中。希望这可以帮助你:)。