以下是我上传图片和使用相应图片名称更新数据库的代码。
上传工作正常,但在更新mysql数据库的语法方面存在一些问题。
function storeimage()
{
$files = array();
$target_path1 = $_FILES['file1']['tmp_name'];
$target_path2 = $_FILES['file2']['tmp_name'];
$target_path3 = $_FILES['file3']['tmp_name'];
$files = array(1=>'file1',2=>'file2',3=>'file3');
//uploadimages($files)
//$target_path = "images/";
foreach($files as $data)
{
$target_path = $_FILES[$data]['name'];
if(move_uploaded_file($_FILES[$data]['tmp_name'], "images/".$target_path))
{
$publish = $_POST['publish'];
$databaseupdate = "INSERT INTO `uploadfiles`.`uploads`
(`id`, `name1`, `name2`, `name3`, `publish`)
VALUES (NULL, '$files['file1']','$files['file2']','$files['file3']','$publish')";
$mysqlupdate = mysql_query($databaseupdate);
echo "The file ". basename($_FILES[$data]['name']).
" has been uploaded<BR>";
}
else
{
echo "There was an error uploading the file, please try again!";
}
$target_path ="";
}
}
答案 0 :(得分:0)
您遇到问题的是PHP语法,而不是SQL。
$sql = "INSERT INTO uploads
VALUES (NULL,'$files[file1]','$files[file2]','$files[file3]','$publish')";
会起作用。
然而,这不仅仅是你的问题 您似乎正在插入未存在的变量,并且不会为查询清理它们。 并且您尝试在一个查询中插入所有三个并运行三次。 看起来您可能想要在循环之外移动查询。
$names = array();
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], "images/".$file['name']))
{
$names[] = $file['name'];
} else {
$names[] = '';
}
}
if (array_filter($names)) { // at least one file uploaded successfully
$publish = mysql_real_escape_string($_POST['publish']);
foreach ($names as $i => $name) {
$names[$i] = mysql_real_escape_string($name);
}
$sql = "INSERT INTO uploads VALUES (NULL,'$files[0]','$files[1]','$files[2]','$publish')";
mysql_query($sql) or trigger_error(mysql_error().$sql);
}
类似这样的事情
答案 1 :(得分:0)
首先,为什么要使用$files['file1']
等来尝试获取文件名?你不应该使用$_FILES[$data]['name']
吗?或$_FILES['file1']['name'], $_FILES['file2']['name']
等
您的SQL也存在一些引用问题。这样的事情怎么样:
$databaseupdate = "INSERT INTO `uploadfiles`.`uploads`
(`id`, `name1`, `name2`, `name3`, `publish`)
VALUES (NULL, '" . $_FILES['file1']['name'] .
"','" . $_FILES['file2']['name'] .
"','" . $_FILES['file3']['name'] ."','$publish')";
其次,您正在迭代'file1','file2'和'file3',但您似乎试图将它们全部插入到表中的一行中。如果您有三个文件,并且想要将它们全部插入到数据库中,那么您是否应该为每个文件插入一行?在这种情况下,表只需要一个“名称”列。