mysql:用户个人资料图片未保存在数据库中,

时间:2018-02-02 09:44:45

标签: php mysqli

A.o.A   我正在处理用户个人资料页面,当我上传图片时没有保存在数据库中而没有在浏览器中显示,只保存在上传文件夹中

<?php
    $db = mysqli_connect("localhost", "root", "", "jobsdb");
    if (isset($_POST['upload'])) 
    {
      $image = $_FILES['image']['name'];

      $sql = "update users set user_image='$image' where 
    username='$user_id'";
      mysqli_query($db, $sql);

      $target = "uploads/".basename($image);
      echo $_SESSION['user_id'];

     if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) 
     {
       $msg = "Image uploaded successfully";
     }  else
        {
          $msg = "Failed to upload image";
        }
    }
    $result = mysqli_query($db, "SELECT * FROM users WHERE 
    user_image='image'");

  ?>

  <?php
    while ($row = mysqli_fetch_array($result)) 
    {
      echo "<img src='uploads/".$row['user_image']."' >";
    }
  ?>

4 个答案:

答案 0 :(得分:0)

  <?php

    session_start();//missing
    $db = mysqli_connect("localhost", "root", "", "jobsdb");
    if (isset($_POST['upload'])) 
    {
  $image = $_FILES['image']['name'];
  $user_id = $_SESSION['user_id'];//initialize the variable 
  $sql = "update users set user_image='$image' where 
username='$user_id'";
  mysqli_query($db, $sql);

  $target = "uploads/".basename($image);


 if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) 
 {
   $msg = "Image uploaded successfully";
 }  else
    {
      $msg = "Failed to upload image";
    }
}
$result = mysqli_query($db, "SELECT * FROM users WHERE 
user_image='$image'");

 while ($row = mysqli_fetch_array($result)) 
 {
  echo "<img src='uploads/".$row['user_image']."' >";
  }
?>

答案 1 :(得分:0)

您保存值user_image的列的类型是什么?

您还可以为图像制作base64_encode,如

$data = file_get_contents('uploads/'.basename($image));
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data); 

并将其作为 LONGTEXT 类型存储在您的数据库中,因此您也不需要将其存储在文件夹中。

答案 2 :(得分:0)

使用

session_start(); //to initiate session before executing php script.  
ini_set('upload_max_filesize', '10M');  //Check the image size which to be uploaded

尝试在服务器中创建要存储图像的文件夹。将文件上传到特定文件夹并在数据库列中仅存储相关路径

答案 3 :(得分:0)

将以下行放在屏幕顶部:

error_reporting(E_ALL); ini_set('display_errors', 1);

检查数据库连接:

<?php
    $db_username = "db_username";  // Your database login username 
    $db_password = "db_password";  // Your database login password
    $db_name = "db_name";      // The name of the database you wish to use
    $db_host = "db_host";   // The address of the database. Often this is 
    localhost, but may be for example db.yoursite.com
    $conn = new mysqli($db_host, $db_username, $db_password, $db_name);
    if (mysqli_connect_errno())
      {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
?>

你收到"Image uploaded successfully"消息吗?