将图像从 html 表单输入上传到数据库 blob 列

Uploading an image from an html form input to database blob column

提问人:KALIL 提问时间:4/10/2022 更新时间:4/10/2022 访问量:1278

问:

我想将数据从 html 表单上传到数据库,这是我的 html 代码:

<form method="post" action="events.php" id="formhh" enctype="multipart/form-data">
    <input type="text" name="Titre" required>
    <input type="file" accept="image/jpeg" name="Image" required>
    <textarea name="Description" form="formhh" required></textarea>
    <div>
        <input type="radio" name="style" value="1" required>
        <input type="radio" name="style" value="2" required>
        <input type="radio" name="style" value="3" required>
        <input type="radio" name="style" value="4" required>
        <input type="radio" name="style" value="5" required>
    </div>
    <input type="submit" class="btn btn-outline-primary me-5">
</form>

以及连接数据并将其发送到数据库的“events.php”(名为“isticg”):

<?php

$conn = new mysqli("localhost", "root", "", "isticg");

$Titre = $_POST['Titre'];
$Img = mysqli_real_escape_string($conn ,file_get_contents($_FILES['Image']['tmp_name']));
$Desc = $_POST['Description'];
$Style = $_POST['style'];



$stmt = $conn->prepare("insert into evenements(Titre, Image, Description,style) values(?,?,?,?)");

$stmt->bind_param("sbsi",$Titre,$Img,$Desc,$Style);

$stmt->execute();

$stmt->close();
$conn->close();

?>

除了图像之外,一切正常,这是我做测试后它在 phpMyadmin 中的样子

我是一个初学者,刚刚开始为这个项目学习php,所以如果你能提供你的答案的解释,请。

php html 表单 mysqli blob

评论

0赞 Your Common Sense 4/10/2022
作为初学者,您应该做的最后一件事就是将 blob 存储在数据库中。
0赞 KALIL 4/10/2022
没有找到另一种方式在那里存储图像,所以..如果您有任何建议,请告诉我
0赞 Your Common Sense 4/10/2022
认真地?没有一个建议只是将文件复制到它所属的位置 - 文件系统中的某个目录?
0赞 Your Common Sense 4/10/2022
帮自己一个忙,与其做一些不自然的事情,不如学习一些基本的东西。比如调试。在责怪数据库不存储您的文件之前,请花点时间验证您是否向该数据库发送了任何内容。之后,继续将映像存储在它所属的位置 - 在文件系统中。
0赞 Your Common Sense 4/10/2022
总是一次只做一件事。没有“将图像从 html 表单输入上传到数据库 blob 列”之类的东西。您只能将HTML表单内容上传到Web服务器。所以你必须这样做。并验证每个表单元素是否已正确上传。只有在那之后,才能继续存储这些数据。一次做一件事。

答:

-2赞 KALIL 4/10/2022 #1

修好了! 我将 php 代码更改为:

<?php

$dbh = new PDO("mysql:host=localhost;dbname=isticg", "root", "");

$Titre = $_POST['Titre'];
$Img = file_get_contents($_FILES['Image']['tmp_name']);
$Desc = $_POST['Description'];
$Style = $_POST['style'];



$stmt = $dbh->prepare("insert into evenements values('',?,?,?,?)");

$stmt->bindParam(1,$Titre);
$stmt->bindParam(2,$Img);
$stmt->bindParam(3,$Desc);
$stmt->bindParam(4,$Style);

$stmt->execute();

?>

评论

0赞 Zach Jensz 4/10/2022
可以解释代码