php - 如何将输入、文本区域和图像上传插入数据库
问题描述
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 的新手
解决方案
您在以下行中有另一个错字。它将是 $_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”的文件夹。
推荐阅读
- javascript - 简单的 javascritp 幻灯片 - 添加控件
- java - java Mail API 用于从 java 程序发送电子邮件,但显示 SMTP 协议错误
- angularjs - 控制器值未绑定到角度 js 中的 HTML
- memory-management - 链接器错误:“地址错误
对于零页符号 “! - grafana - Prometheus / Grafana 最高价值和时间
- sql-server - SQL Server如何在table1更新时将数据填充到table2
- javascript - 过滤搜索对象的特定属性
- mysql - Mysql 5.6 Replication Lag 在 0 和 n 之间波动
- git - Git 分支名称更改已提交但未推送到原点
- php - PHP Curl 请求失败但在其他客户端中有效