如何在数据库中获取Mysqli图像以显示在div中

时间:2014-05-13 16:59:20

标签: php image

我希望图像显示的div(表单发送到send_post.php):

<div style="width:200px ; height: 200px ; border:1px dashed red ; display:inline-block ; margin-top:5px ; margin-left:5px" class="postedBy"></div><!--end image-->

上述div位于此容器div中:

<div style="height:800px ; width:800px  ; border:1px dashed black ; margin-left:200px ; float:left ; margin-top:50px" id= "profilePosts"></div>

send_post.php中的代码:

<?php

session_start();

    if(!isset($_SESSION['username']))   {
    header('location: mustLogin.php');
} else  {
    $username = $_SESSION['username'];
}

$title = $_POST['title'];
$description = $_POST['description'];
$image = $_POST['image'];
$dateAdded = date('Y-m-d');
$addedBy = $username;

if (!empty('title') && !empty('description') && !empty('image')) {
//establish connection to SQL
$conn = mysqli_connect("localhost", "root", "") or die ("Couldn't connect to SQLI");
//connect to DB
mysqli_select_db($conn, "accounts") or die ("Couldn't find DB");

$sqliCommand = "INSERT INTO `posts` (title, description, image, date_added, added_by) VALUES ('$title', '$description', '$image', '$dateAdded', '$addedBy')" or die ('Info couldnt go to database');

mysqli_query($conn, $sqliCommand) or die ('MySQLI error');

header('location: profile.php?user='.$username);

} else  {

    header('location: error.php');
}

&GT;

将信息发送到数据库就好了,但有人可以向我解释如何将用户添加的图像(所有这些)添加到我列出的第一个div中显示?

2 个答案:

答案 0 :(得分:1)

您需要创建一个单独的网址,只是为了通过标题中的图片类型来从DB返回检索到的图像 因此,在for循环中选择之后,您可以使用类似

的内容
<?php
$sqliCommand = "SELECT * FROM `posts` WHERE `added_by` = '{$this->username}'";
$result = mysqli_query($conn, $sqliCommand);
while ($row = mysqli_fetch_assoc($result)) {
?>
   <div style="width:200px ; height: 200px ; border:1px dashed red ; display:inline-block ; margin-top:5px ; margin-left:5px" class="postedBy">
      <img src="/imgView.php?imgId=<?php echo $row['id'] ?>"
   </div>
<?php
}
?>

现在您需要为 imgView.php 创建一个页面,其中包含类似

的内容
<?php
  $imgId = $_GET['imgId'];
  if (!empty($imgId)) {
     $sqliCommand = "SELECT `image` FROM `posts` WHERE `id` = '$imgId'";
     $result = mysqli_query($conn, $sqliCommand);
     $row = mysqli_fetch_assoc($result));

     header("Content-Type: image/jpeg"); // or whatever the correct content type is.
     echo $row['image']; //if your image is encoded you can decode it here, too.
  }
?>

我还建议您在插入时保存MIME类型,以便能够使用正确的标题Content-Type

答案 1 :(得分:0)

上传表单:

<form action="/image_upload.php" method="POST" enctype="multipart/form-data">
    <label>Title:</label>
    <input type="text" name="title">;
    <label>Description:</label>
    <textarea name="description"></textarea>
    <label>Upload Image:</labe>
    <input type="file" name="avatar" accept="image/*">
    <button type="submit">Upload</button>
</form>

上传脚本(image_upload.php):

session_start();

if(!isset($_SESSION['username'])) 
{
    header('location: mustLogin.php');
    exit;
} 
else 
{
    if($_FILES != null) //uploaded files are held in $_FILES array
    {
        $username = $_SESSION['username'];

        $title = $_POST['title'];
        $description = $_POST['description'];
        $dateAdded = date('Y-m-d');
        $addedBy = $username;   
        if ($title != "" && $description != "" && !empty($_FILES))
        {
            $new_file_name = uniqid() . "-" . $username . "-upload";
            $file_path = 'images/' . $new_file_name; //images haves to be a directory in the same directory that this script runs
            $uploaded_file = move_uploaded_file($_FILES['tmp_name'],  $file_path ); 
            if($uploaded_file == TRUE)
            {
                $conn = mysqli_connect("localhost", "root", "") or die ("Couldn't connect to SQLI");
                //connect to DB
                mysqli_select_db($conn, "accounts") or die ("Couldn't find DB");

                /* You should change this while query to a prepared statement for security reasons */
                $sqliCommand = "INSERT INTO `posts` (title, description, image, date_added, added_by) VALUES ('$title', '$description', '$file_path', '$dateAdded', '$addedBy')" or die ('Info couldnt go to database');

                mysqli_query($conn, $sqliCommand) or die ('MySQLI error');  

                header('location: profile.php?user='.$username);    
            }
            else
            {
                echo "Could not upload file.";
            }
        }
        else
        {
            echo "Missing title or description, or file array is empty.";
        }
    }
    else
    {
        echo "No file uploaded.";
    }
}

在个人资料中显示图片:

session_start();
$username = $_SESSION['username'];
$conn = new mysqli("localhoast", "root", "", "accounts") or die('Connect Error (' . $conn->connect_errno . ') ' . $conn->connect_error);
$sql = "SELECT * FROM `posts` WHERE added_by = ?";
$query = $conn->stmt_init();
$query = $query->prepare($sql);
$query->bind_param('s',$username);
$query->execute();
$images = $query->get_result();
if($images->num_rows > 0)
{
    while($image = $images->fetch_assoc())
    {
    ?>
    <div style="width:200px ; height: 200px ; border:1px dashed red ; display:inline-block ; margin-top:5px ; margin-left:5px" class="postedBy">
        <img src="<?php echo $image['image']; ?>">
    </div><!--end image-->
    <?php
    }
}

您应该将图像上传到目录,然后跟踪这些图像在数据库中的位置。然后只需从您从数据库中获取的信息链接到这些图像。我没有测试这个,但算法应该都在那里。我建议将插入查询更改为准备好的语句,就像我在配置文件部分中使用的那样,您可能希望查看https://github.com/samayo/bulletproof之类的内容,以确保人们不上传实际上不是图像的文件。