我正在尝试创建一个将用户数据插入数据库表并上传文件的表单,但是我不知道如何将文件添加到数据库中。表单数据输入没有问题,只是文件没有问题。任何帮助,将不胜感激。
PHP表单:
<form method="post" action="index.php" id="frm_add" enctype="multipart/form-data">
<input type="hidden" value="add" name="action" id="action">
<div class="form-group">
<label for="medID" class="control-label">ID</label>
<input type="hidden" class="form-control" id="medID" name="medID"/>
</div>
<div class="form-group">
<label for="emp_id" class="control-label">Employee No:</label>
<input type="text" class="form-control" id="emp_id" name="emp_id"/>
</div>
<div class="form-group">
<label for="name" class="control-label">Full Name:</label>
<input type="text" class="form-control" id="name" name="name"/>
</div>
<div class="form-group">
<label for="title" class="control-label">Job Title:</label>
<input type="text" class="form-control" id="title" name="title"/>
</div>
<div class="form-group">
<label for="documents" class="control-label">Supporting Documents:</label>
<input type="file" name="documents" class="form-control">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_add" class="btn btn-primary">Save</button>
</div>
</form>
insert.php
<?php
//include connection file
include_once("connection2.php");
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$empCls = new Student($connString);
switch($action) {
case 'add':
$empCls->insertStudent($params);
break;
case 'edit':
$empCls->updateStudent($params);
break;
case 'delete':
$empCls->deleteStudent($params);
break;
default:
$empCls->getStudents($params);
return;
}
class Student {
protected $conn;
protected $data = array();
function __construct($connString) {
$this->conn = $connString;
}
public function getStudents($params) {
$this->data = $this->getRecords($params);
echo json_encode($this->data);
}
function insertStudent($params) {
$data = array();
$sql = "INSERT INTO `employee` (emp_id, name, title, documents) VALUES('" . $params["emp_id"] . "', '" . $params["name"] . "','" . $params["title"] . "', '" . $params["documents"] . "'); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert student data");
}
我做错了什么,我需要添加什么文档?任何帮助将不胜感激。
谢谢
答案 0 :(得分:1)
将文件保存在数据库内部毫无意义。仅获取文件名,
$info = pathinfo($_FILES['userFile']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext;
$target = 'images/'.$newname;
move_uploaded_file( $_FILES['userFile']['tmp_name'], $target);
上面的代码来自这里:How to upload & Save Files with Desired name
因此,您需要做的是将名称保存在数据库中,而不是仅使用带有表示“名称”的文件的路径访问该名称。