php - 如何将图像添加到 sql 数据库
问题描述
我正在尝试将标题、描述和图像插入到 sql 数据库中,下面是表格。但是,提交表单后代码会中断。我被重定向到下一页,但下一个文件中的任何代码都没有得到处理。
在我添加添加图像的功能并且只有文本之前它工作正常。
这是未正确处理的表单的代码:
<?php
if (isset($_SESSION['username'])) {
echo "<form action='/origo/addnewtopic.php?cid=".$_GET['cid']."&scid=".$_GET['scid']."'
method='POST' enctype='multipart/form-data'>
<p>Titel: </p>
<input type='text' id='topic' name='topic' size='100' />
<p>Innehåll: </p>
<textarea id='content' name='content'></textarea><br />
<input type='file' name='image'>
<input type='submit' value='Lägg till' name='submit'/></form>"; ?>
如果有人想知道,这是它发送信息的文件,它试图将文本和图像插入数据库,但这些都没有得到处理。
<?php
session_start();
include ('dbconn.php');
$topic = addslashes($_POST['topic']);
$content = nl2br(addslashes($_POST['content']));
$image = ($_FILES['image']);
$cid = $_GET['cid'];
$scid = $_GET['scid'];
$insert = mysqli_query($con, "INSERT INTO topics (`category_id`, `subcategory_id`, `author`, `title`, `content`, `date_posted`)
VALUES ('".$cid."', '".$scid."', '".$_SESSION['username']."', '".$topic."', '".$content."', NOW());");
$tid = mysql_insert_id();
die($tid);
if($image) {
$insert2 = mysqli_query($con, "INSERT INTO images (`category_id`, `subcategory_id`, `topic_id`, `image`)
VALUES ('".$cid."', '".$scid."', '".$tid."', '".$image."');
}
else {
die("no image");
}
if ($insert) {
header("Location: /origo/topics.php?cid=".$cid."&scid=".$scid."");
} else {
die("error");
}
?>
解决方案
尝试在数据库中使用 blob 数据类型。也在这里
$content = nl2br(addslashes($_POST['content']));
您必须使用 $_FILES 而不是 $_POST。由于图像之类的文件存储在数组 $_FILES 中,该数组稍后将被提取。此外,您必须将 file_get_contents 用于:
$content = nl2br(addslashes(file_get_contents($_POST['content'])));
希望这有所帮助
推荐阅读
- vb.net - 使用 docx body VB 创建 MailMessage 时出错
- sql - 从 SQL Server 中的 nvarchar 类型列中提取特定字符串
- python - 在python中将符号表达式转换为数组
- azure - Azure Durable Functions - HTTP Starter 安装
- pdf - 使用 ps2pdf 后出现背景网格
- rust - Serde 使用公共字段在内部标记枚举
- android - ViewGroup.findViewById() 返回 null 因为视图在运行时具有不同的 id
- php - Laravel 将数据从一种形式保存到不同的数据库表中
- postgresql - 错误:无法创建没有“date_time”列的唯一索引(用于分区)
- php - 如何让我的 PHP 代码在 Wordpress 的 img src 中工作?