将图像上传到mysqli数据库的问题

时间:2015-03-08 16:30:18

标签: php html mysql mysqli

由于我添加了上传图片的功能,我的脚本不再有效了。这意味着我无法在数据库中插入新帖子。 请帮我解决这个问题,谢谢!如需更多问题,请使用以下评论部分:)

PHP:

<?php
session_start();
header('content-type: text/html; charset=utf-8');
$uname = $_POST['username'];
$typ = $_POST['typ'];
$titel = $_POST['titel'];
$content = $_POST['content'];
$timestamp = time();

$db = new mysqli("localhost", "...", "...", "...");
if($db->connect_errno > 0){
    die("Unable to connect to database: " . $db->connect_error);
}

if(is_uploaded_file($_FILES['image']['tmp_name'])) {
        // Verweis auf Bild
        $image = $_FILES['image']['tmp_name'];

        // Vorbereiten für den Upload in DB
        $data = addslashes(file_get_contents($image));

        // Metadaten auslesen
        $meta = getimagesize($image);
        $mime = $meta['mime'];
}

//create a prepared statement
$stmt = $db->set_charset("utf8");
$stmt = $db->prepare("INSERT INTO artikel (`red`, `typ`, `titel`, `content`, `image`, `mimetype`, `timestamp`) VALUES (?,?,?,?,?,?,?)");

//bind the username and message
$stmt->bind_param('sssssss', $uname, $typ, $titel, $content, $data, $mime, $timestamp);

//run the query to insert the row
$stmt->execute();

header("Location: erfolg.php");

?>

html表格:

<form name="form2" action="insert.php" method="post">
Username:<br>
<input style="width:100%;" type="text" accept-charset="utf-8" name="username" value="<?php echo $_SESSION['username']; ?>" class="login_form" readonly><br><br>
Typ:<br>
<input style="width:100%;" type="text" name="typ" value="blog" class="login_form" readonly><br><br>
Titel:<br>
<input style="width:100%;" type="text" placeholder="Überschrift, z.B. Die Kunst des Spickens" name="titel"><br><br>
Inhalt:<br>
<textarea style="width:100%; height:250px; font:Arial, Helvetica, sans-serif !important;" type="text" placeholder="Inhalt" name="content"></textarea><br><br>
Bild anhängen (maximal 1 Bild):<br>
<input name="image" type="file"><br><br>
<input type="submit" value="Eintragen">
</form>

所以,这是php和html,谢谢你的帮助!

抱歉英语不好

1 个答案:

答案 0 :(得分:0)

首先,您的表单需要使用enctype =“multipart / form-data”来上传文件。

其次,从temp目录移动上传的文件并将路径保存在数据库中,而不是保存临时图像的完整二进制数据不是一个想法吗?

http://php.net/manual/en/function.move-uploaded-file.php