如何将发布或插入照片或文本的方式分开到我的数据库,即mysql数据库。
在这行代码中,我可以将图片和文本一起发布,但如果我只想要一张图片,则会在代码中显示错误。
<?php
include('includes/database.php');
include('session.php');
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}else{
$file=$_FILES['image']['tmp_name'];
$image = $_FILES["image"] ["name"];
$image_name= addslashes($_FILES['image']['name']);
$size = $_FILES["image"] ["size"];
$error = $_FILES["image"] ["error"];
if ($error > 0){
die("Error uploading file! Code $error.");
}else{
if($size > 10000000){ //conditions for the file
die("Format is not allowed or file size is too big!");
}else{
move_uploaded_file($_FILES["image"]["tmp_name"],"upload/" . $_FILES["image"]["name"]);
$location="upload/" . $_FILES["image"]["name"];
$user=$_SESSION['id'];
$content=$_POST['content'];
$time=time();
$update=mysql_query(" INSERT INTO post (user_id,post_image,content,created)
VALUES ('$id','$location','$content','$time') ") or die (mySQL_error());
}
header('location:home.php');
}
}
?>
这是与上述代码相对应的表格。
<div id="right-nav">
<h1>Update Status</h1>
<form method="post" action="post.php" enctype="multipart/form-data">
<textarea placeholder="Whats on your mind?" name="content" class="post-text" required></textarea>
<input type="file" name="image">
<button class="btn-share" name="Submit" value="Log out">Share</button>
</form>
</div>
感谢您将来的答案。
答案 0 :(得分:0)
保存图像或文本或两者:
<?php
include('includes/database.php');
include('session.php');
$user=$_SESSION['id'];
$time=time();
// Content
if( isset($_POST['content']) && !empty($_POST['content']) ){
$content=$_POST['content'];
}else{
$content="";
}
// Image
if ( isset($_FILES['image']['tmp_name']) && !empty($_FILES['image']['tmp_name']) ) {
$file=$_FILES['image']['tmp_name'];
$image = $_FILES["image"] ["name"];
$image_name= addslashes($_FILES['image']['name']);
$size = $_FILES["image"] ["size"];
$error = $_FILES["image"] ["error"];
if ($error > 0){
die("Error uploading file! Code $error.");
}
if($size > 10000000){ //conditions for the file
die("Format is not allowed or file size is too big!");
}
move_uploaded_file($_FILES["image"]["tmp_name"],"upload/" . $_FILES["image"]["name"]);
$location="upload/" . $_FILES["image"]["name"];
}else{
$location="";
}
// Save to database if there is content OR an image
// Will save both if both are present
if( !empty($content) || !empty($location) ){
$update=mysql_query(" INSERT INTO post (user_id,post_image,content,created)
VALUES ('$id','$location','$content','$time') ") or die (mySQL_error());
// Redirect to home
header('location:home.php');
}
?>
在所有情况下,都会设置SQL查询所需的变量 所以应该没有错误。
如果没有文字且没有图像,则脚本什么都不做。