首页 > 解决方案 > 如何将图像添加到 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");
      }
?>

标签: phphtmlmysqlsqlforms

解决方案


尝试在数据库中使用 blob 数据类型。也在这里

$content = nl2br(addslashes($_POST['content']));

您必须使用 $_FILES 而不是 $_POST。由于图像之类的文件存储在数组 $_FILES 中,该数组稍后将被提取。此外,您必须将 file_get_contents 用于:

$content = nl2br(addslashes(file_get_contents($_POST['content'])));

希望这有所帮助


推荐阅读