我已经创建了一个表单,并希望将所有信息存储在PHPMyAdmin中。我设法存储了其他信息,但没有存储图像文件。即使在我提交表单时声明已提交,它在PHPMyAdmin的image列下也没有任何内容。
form2.php
<!DOCTYPE html>
<html>
<head>
</head>
<h1>Found Items Handover</h1>
<br>
<div class="container">
<div class="row">
<h2>1. Details of Handover Personnel </h2>
</div>
<form action="insert2.php" method="post" enctype="multipart/form-data">
<div class="row input-container">
<div class="col-md-6 col-sm-12">
<div class="styled-input">
<input type="text" name="name"required />
<label>Staff Name</label>
</div>
</div>
<div class="col-md-6 col-sm-12">
<div class="styled-input" style="float:right;">
<input type="text" name="staffno" required />
<label>Staff Number</label>
</div>
</div> <br>
<div>
<label>Attachment:</label><input type='file' name='file'><br>
</div>
</div>
<br><input type="submit" name="submit" value="submit">
</form>
inser2.php
<?php
$con= mysqli_connect('127.0.0.1','root','','satsform1');
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'satsform1'))
{
echo 'Database Not Selected';
}
$name = $_POST['name'];
$staffno = $_POST['staffno'];
$sql = "INSERT INTO handover (name,staffno)
VALUES ('$name','$staffno')";
if(isset($_POST['submit'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Insert record
$query = "insert into images(name) values('".$name."')";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
if(!mysqli_query($con,$sql))
{
echo 'Not Submitted';
}
else
{
echo 'Submitted';
}
?>
我希望在提交表单时将图像的URL存储在PHPMyAdmin中。
答案 0 :(得分:0)
请在insert2.php文件中插入以下代码,并加上各自的变量和文件名。
<?php
$con= mysqli_connect('localhost','root','','join');
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'join'))
{
echo 'Database Not Selected';
}
$target_dir = "uploads/";
echo "<br>";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
echo "<br>";
$name = $_POST['name'];
$staffno = $_POST['staffno'];
// get details of the uploaded file
$fileTmpPath = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
$allowedfileExtensions = array('jpg', 'gif', 'png','jpeg');
if (in_array($fileExtension, $allowedfileExtensions)) {
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
echo "File uploaded successfully!";
$query = "INSERT INTO user (image)
VALUES ('$target_file')";
mysqli_query($con,$query);
if(!mysqli_query($con,$query))
{
echo 'Not Submitted';
}
else
{
echo 'Submitted';
}
} else{
echo "Sorry, file not uploaded, please try again!";
}
}
?>