用php将图像上传到mysql数据库
我得到了我的用php将图像上传到mysql数据库,php,mysql,database,forms,Php,Mysql,Database,Forms,我得到了我的insert.php文件: <?php // Above is code for connection // echo "succesful connection"; $image = addslashes(file_get_contents($_FILE['image']['tmp_name'])); $image_name = addslashes($_FILES['image']['name']); $sql = "INSERT INTO `myTable` (`id
insert.php
文件:
<?php
// Above is code for connection //
echo "succesful connection";
$image = addslashes(file_get_contents($_FILE['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `myTable` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) {
echo "Something went wrong! :(";
}
?>
<form action="insert.php" method="POST" enctype="multipart/form-data">
<label>File: </label><input type="file" name="image" />
<input type="submit" />
</form>
当我想上传图像时,我遇到了一个错误:
“警告:file_get_contents()[function.file get contents]:文件名在/myDomain.com/insert.php中不能为空”
更新: 我把它缩短为:
<?php
$content = base64_encode(file_get_contents($_FILES['image']['tmp_name']));
$sql = "INSERT INTO `myTable` (`id`, `image`) VALUES ('1', '{$content}')";
if (!mysql_query($sql)) {
echo "Something went wrong! :(";
?>
始终添加检查以确保您实际得到了一些东西
您可以这样使用它:
<?php
if(is_uploaded_file($_FILES['image']['tmp_name']){
echo "succesful connection, we have an image!";
//get the image name, no need for slashes
$image_name = basename( $_FILES['image']['name']);
//perform the the INSERT HERE
//........
}else{
echo "Nothing was uploaded";
}
?>
在大多数情况下,您不希望将文件真正存储在数据库中。您只想保存路径
如果这是您想要的,那么这个脚本就应该这样做
// Get destination
$destination = 'path/to/folder' . $_FILES['image']['name'];
// Upload file
move_uploaded_file($_FILES['image']['tmp_name'], $destination);
// Get name
$image_name = addslashes($_FILES['image']['name']);
// Query
$sql = "INSERT INTO `myTable` (`id`, `image`, `image_name`) VALUES ('1', '{$destination}', '{$image_name}')";
if (!mysql_query($sql)) {
echo "Something went wrong! :(";
}
首先,为什么要将图像插入数据库?很少有实际意义的用例。你忘记了最大文件大小隐藏字段,你做的一切都错了addslashes
不会让人们上传恶意脚本,而不是文件名。我甚至不知道你的想法。另外,如果您懒惰,那么您的数据库极易受到sql注入的攻击,像“什么和为什么”这样的问题根本帮不上我的忙。这是为了测试,首先我要做,然后我会关心其他事情。在这种形式下它不起作用,但它应该。。。根据很多例子,你应该使用$\u文件
,而不是$\u文件
。