mysql - How to insert the data if the image field is empty using php -
hi trying data title,description , image.if give title , description without adding image data should inserted database.but if trying getting error.here error , code:
error: error while uploading
my code
$title=$_post['blog_title']; $result = str_replace(" ", "-", $title); $description=$_post['blog_description']; $name=$_files["image"]["name"]; $type=$_files["image"]["type"]; $size=$_files["image"]["size"]; $temp=$_files["image"]["tmp_name"]; $error=$_files["image"]["error"]; if($error>0) die("error while uploading"); else { if($type == "image/png" || $type == "image/jpg"|| $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe" ) { move_uploaded_file($temp,"upload/".$name); $sql=mysql_query("insert blogs(image,blog_title,blog_description)values('$name','$result','$description')"); echo "upload complete"; session_start(); header("location:blogimage.php"); } else { echo "failure"; }
html code
<form method="post" action="blogs.php" enctype="multipart/form-data"> <div> <label for="title">title</label> <input type="text" name="blog_title" value=""> </div> <div> <label for="image">image</label> <input type="file" name="image"> </div> <div> <label for="blog_description">description</label> <textarea name="blog_description" class="text" style="width:50%;"> </textarea> </div> <input type="submit" value="submit"/> </form>
first of all, start session @ top of php script, this:
<?php session_start(); ?>
and comes issue. first use is_uploaded_file()
function check whether file uploaded or not, , process form accordingly.
so code should this:
$title=$_post['blog_title']; $result = str_replace(" ", "-", $title); $description=$_post['blog_description']; if(is_uploaded_file($_files['image']['tmp_name'])){ $name=$_files["image"]["name"]; $type=$_files["image"]["type"]; $size=$_files["image"]["size"]; $temp=$_files["image"]["tmp_name"]; $error=$_files["image"]["error"]; $ext = strtolower(pathinfo($name, pathinfo_extension)); if($error > 0){ die("error while uploading"); }else{ $permissible_extension = array("png", "jpg", "jpeg", "svg", "jpe"); if(in_array($ext, $permissible_extension)){ if(move_uploaded_file($temp,"upload/".$name)){ $sql = mysql_query("insert blogs(image,blog_title,blog_description)values('$name','$result','$description')"); if($sql){ header("location:blogimage.php"); exit(); }else{ echo "insertion failed"; } }else{ echo "file couldn't uploaded"; } }else{ echo "invalid format"; } } }else{ $sql = mysql_query("insert blogs(blog_title,blog_description)values('$result','$description')"); if($sql){ header("location:blogimage.php"); exit(); }else{ echo "insertion failed"; } }
sidenote: don't use mysql_*
functions, deprecated of php 5.5 , removed altogether in php 7.0. use mysqli
or pdo
instead. and why shouldn't use mysql_*
functions.
Comments
Post a Comment