Php 复制图像,但只执行一个查询
我在mysql中插入时遇到问题。 此函数应将图像传输到images文件夹,并为每个图像创建一个新查询,因此,如果有3个图像,则执行3个查询,但只执行第一个查询Php 复制图像,但只执行一个查询,php,mysql,Php,Mysql,我在mysql中插入时遇到问题。 此函数应将图像传输到images文件夹,并为每个图像创建一个新查询,因此,如果有3个图像,则执行3个查询,但只执行第一个查询 public function insertNews($author, $subject, $content) { if($this->databaseConnection()) { // * So this is initalizing our database, now al
public function insertNews($author, $subject, $content)
{
if($this->databaseConnection())
{
// * So this is initalizing our database, now all we have to do is create a simple query.
$unique_id = bin2hex(random_bytes(3));
$insert_news = $this->db_connection->prepare("INSERT INTO news (author, subject, content, time, uniqueid) VALUES (:author, :subject, :content, NOW(), :id)");
$insert_news->bindValue(':author', $author, PDO::PARAM_STR);
$insert_news->bindValue(':subject', $subject, PDO::PARAM_STR);
$insert_news->bindValue(':content', $content, PDO::PARAM_STR);
$insert_news->bindValue(':id', $unique_id, PDO::PARAM_STR);
$insert_news->execute();
// * Checking if any images are waiting to be uploaded
if(isset($_FILES['images']) && !empty($_FILES['images']['name']))
{
$extension = array("jpeg", "jpg", "png", "gif");
$insert_images = $this->db_connection->prepare("INSERT INTO news_images (news_id, location) VALUES (:id, :location)");
foreach($_FILES['images']['tmp_name'] as $key => $tmp_name)
{
$file_name = $_FILES["images"]["name"][$key];
$file_tmp = $_FILES["images"]["tmp_name"][$key];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$tname = bin2hex(random_bytes(10));
$temp = explode(".", $_FILES['images']['name']);
$newfilename = $tname . '_news.' . $ext;
$location = "images/".$newfilename;
if(in_array($ext, $extension))
{
if(!file_exists($location))
{
// * Now we have to upload it to the database
$insert_images->bindValue(':id', $unique_id, PDO::PARAM_STR);
$insert_images->bindValue(':location', $location, PDO::PARAM_STR);
$insert_images->execute();
// * moving file
move_uploaded_file($file_tmp = $_FILES["images"]["tmp_name"][$key], $location);
}
}
}
}
header('Location: news.php');
exit();
}
}
你有错误吗?如果没有,请尝试打开错误报告。检查表
news\u images
的架构,并确保列news\u id
上没有唯一的约束。另外,为什么要为每个图像重新准备$insert_images
,而不是在循环之前准备一次?您只根据时间创建新的文件名。您的图像可能存储得很快,其中一些图像的名称相同。为什么要创建变量$location
,只使用一次,而不是第二次?检查两个if条件if(在数组中($ext,$extension)){if(!file_存在(“images/”$newfilename)){
对每个图像是否为真啊,好吧。添加ramdom_字节几乎总是可行的,但它仍然不是100%可靠的。为什么不使用文件计数器($key
?),并将其与新闻id
相结合,这样您就可以确定名称是唯一的,并且名称的信息量更大。