下面是将文件 (fileImage) 上传到文件夹 (ImageFiles) 的部分代码。但我还想做的是使用 INSERT VALUES 代码将文件位置(文件上传到的位置)插入数据库。我希望将文件位置插入到“ImageFile”字段中,对于“ImageId”,我希望它显示字符串“IMG”,然后在字符串后包含一个数字。例如:
在我的数据库表中,如果它是这样的:
ImageId ImageFile
IMG1 ImageFiles/penguins.png
IMG2 ImageFiles/desert.png
IMG3 ImageFiles/jellyfish.jpg
然后,如果我将文件“tulips.png”从我的计算机上传到 ImageFiles 文件夹,那么在数据库中它应该插入如下所示的值:
ImageId ImageFile
IMG4 ImageFiles/tulips.png
但是如何编码呢?下面是我目前的代码,它成功上传了文件并且只包含插入值的部分编码:
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageId, ImageFile)
VALUES ("");
mysql_query($imagesql);
最佳答案
如果您使用 PHP 的 PDO 对象,它将简化您的代码并同时使其更安全(通过使用准备好的语句)。
这是您将如何执行此操作的示例:
首先,将您的 ID 存储为 AUTO_INCREMENT-ed INT 而不是“IMG#”,因为这会使事情变得更容易(然后您不需要插入 ID 值)
DROP TABLE IF EXISTS tbl_img_store;
CREATE TABLE tbl_img_store(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
filename VARCHAR(25) --increase this if you think you need to
) ENGINE=InnoDB;
此外,创建一个表来存储配置设置,使您的数据库更有效率:
DROP TABLE IF EXISTS tbl_img_config;
CREATE TABLE tbl_img_config(
img_path VARCHAR(50)
);
INSERT INTO tbl_img_config (img_path) VALUES ("http://img.mysite.com/?i=");
现在回到 PHP,您可以像这样快速插入大量图像:
# Create a DB connection
$db = new PDO("mysql:host=X.X.X.X;dbname=mydb", $user, $pass);
# Compile an array of image paths
$img1path = "img1.png";
$img2path = "img2.png";
$img3path = "img3.png";
$images = array($img1path, $img2path, $img3path);
# Create a query to insert the paths to the db
$sql = "INSERT INTO tbl_img_store (filename) VALUES (?),(?),(?);";
$query = $db->prepare($sql);
$query->execute($images);
# Check rows affected
$rows = $query->rowCount();
echo "$rows images were saved.";
关于php - 如何在数据库中正确插入这些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10156332/