Php &引用;准备;SQL插入
我在我的网站上有一个文件上传功能,在提交帖子后立即执行 唯一的问题是,如果在提交帖子后上传的文件出现错误,比如文件太大,帖子仍然会被提交 目前,如果文件上传失败,我必须删除插入的帖子,但我认为可能有更好的解决方案 代码如下所示:Php &引用;准备;SQL插入,php,mysql,sql,sql-insert,Php,Mysql,Sql,Sql Insert,我在我的网站上有一个文件上传功能,在提交帖子后立即执行 唯一的问题是,如果在提交帖子后上传的文件出现错误,比如文件太大,帖子仍然会被提交 目前,如果文件上传失败,我必须删除插入的帖子,但我认为可能有更好的解决方案 代码如下所示: $query=$con->query('INSERT INTO `posts` (`user`,`comment`) VALUES("'.$user->id.'","'.$comment.'")'); //Submit post $postID = $con
$query=$con->query('INSERT INTO `posts` (`user`,`comment`) VALUES("'.$user->id.'","'.$comment.'")'); //Submit post
$postID = $con->insert_id; //This variable is needed for the file upload
if (empty($error)){ //proceed with file upload
//.....
if (empty($error))
$con->query('DELETE FROM `posts` WHERE `id` = "'.$postID.'" LIMIT 1'); //Delete post if file error
}else{
$con->query('UPDATE `posts` SET `image` =".$imageID." WHERE `id` = "'.$postID.'" LIMIT 1'); //
}
<?php
// If there were not errors during form submission
// As you might know 0 means there are absolutely no errors
if ($_FILES['field_name']['error']) == 0) {
$db->insert(....);
$id = $db->getLastId();
$uploader->upload($_FILES, $id);
} else {
// Just display errors and don't do anything here
}
根据您的用例,您可以在插入之前调用
START TRANSACTION
,在成功时调用COMMIT
,或者在出错时调用ROLLBACK
正如Durbnpoison所指出的,您应该检查查询中的SQL注入
有关文档,请参阅
唯一的问题是如果文件有错误
提交帖子后上传,如文件太小
大,该职位仍将被提交
是的,无论是否有错误,都将始终提交表单。
更好的解决办法是把你的任务变成小任务。所以,换句话说,一定要在表中写入一个图像路径,以防出现错误
将这些单词转换为代码会导致类似这样的结果:
$query=$con->query('INSERT INTO `posts` (`user`,`comment`) VALUES("'.$user->id.'","'.$comment.'")'); //Submit post
$postID = $con->insert_id; //This variable is needed for the file upload
if (empty($error)){ //proceed with file upload
//.....
if (empty($error))
$con->query('DELETE FROM `posts` WHERE `id` = "'.$postID.'" LIMIT 1'); //Delete post if file error
}else{
$con->query('UPDATE `posts` SET `image` =".$imageID." WHERE `id` = "'.$postID.'" LIMIT 1'); //
}
<?php
// If there were not errors during form submission
// As you might know 0 means there are absolutely no errors
if ($_FILES['field_name']['error']) == 0) {
$db->insert(....);
$id = $db->getLastId();
$uploader->upload($_FILES, $id);
} else {
// Just display errors and don't do anything here
}
为什么不先检查一下文件的大小呢?SQL注入不是你的朋友。你愿意这样做。