首页 > 解决方案 > 如何将输入、文本区域和图像上传插入数据库

问题描述

Hye,目前我在视频中关注一些教程,但我不知道我的数据如何不将图片上传到数据库中。

当我将一些数据放入表单并且我的图片仍然没有上传时,这发生在我的数据库中

这是 PHP 中的代码

<?php
$sqlservername = "127.0.0.1";
$sqlusername = "root";
$sqlpassword = "";
$sqldbname ="test";

$conn = new mysqli($sqlservername, $sqlusername, $sqlpassword, $sqldbname);

if($conn->connect_error){
    die("Connection fail");
}

session_start();



if(isset($_POST['li_submit'])){
    $_SESSION['li_username'] = $_POST['username'];

    $li_username = $_SESSION['li_username'];    
}   

if(isset($_POST['submit'])){    
$id = $username = $password = $location = $description = "";

if(isset($_POST['username']))
{
    $id = uniqid($prefix='u_');

    $username = $_POST['username'];

}

if(isset($_POST['password'])){
    $password = $_POST['password'];}

if(isset($_POST['location'])){
    $location = $_POST['location'];
}

if(isset($_POST['description']))
{
    $description = $_POST['description'];
}

if(isset($_FILES['profile_pic'])){
    $target_dir = "IMG_UPLOAD/";

    $target_file = basename($_FILES['profile_pic']["name"]);

    $file_type = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

    $target_path = $target_dir . uniqid($prefix='img.'). "." .$file_type;

    if(!move_uploaded_file($_FILE['profile_pic']['tmp_name'], $target_path)){
        $target_path = "";
    }

    echo $target_path;

}   

$sql_insert = $conn->prepare("insert into user_info(id, username, password, 

location, description, image_path) values (?,?,?,?,?,?)");

$sql_insert->bind_param("ssssss", $id, $username, $password, $location, 

$description, $target_path);

$sql_insert->execute();

$sql_insert->close();

}

$conn->close();

?>

和 HTML 中的这段代码,以防你想看到它

<body>
<h1>Profile</h1>

<form method='post' enctype=''multipart/form-data'>
    <input type='name' name='username' placeholder='Username'/>
    <input type='password' name='password' placeholder='Password'/>
    <input type='test' name='location'placeholder='Location'/>
    <textarea name='description'>Enter about yourself</textarea>
    <input type='file' name='profile_pic'/>
    <input type='submit' name='submit' value='save'/>




</form>

</body>

我希望当我按下保存按钮时,我放置的所有数据都会保存到数据库中,包括基于屏幕截图的图片。请帮助我,我还是 PHP 的新手

标签: php

解决方案


您在以下行中有另一个错字。它将是 $_FILES 而不是 $_FILE。

if(!move_uploaded_file($_FILE['profile_pic']['tmp_name'], $target_path)){

要将数据插入数据库,请使用以下代码:

$sql_insert = mysqli_query($conn, "insert into user_info (username, password, location, description, image_path) values ('$username', '$password', '$location', '$description', '$target_path')");

将 id 设置为主键并自动递增。

还要确保您在包含您的 php 文件的目录中创建了一个名为“IMG_UPLOAD”的文件夹。


推荐阅读