Upload image, insert name and path in database based on value - php

I have the following code which works after submitting my form:
I'm getting the photo which is upload, in my upload folder.
Now I want to Insert this photo name and path in my database.
Example:
If image name is 6.jpg, I want in my database name=6.jpg and path=uploads/6.jpg
html:
<form method="post" enctype="multipart/form-data">
<input type="file" name="foto">
<input type="submit" name="submit">
php:
<?php
if (isset($_POST['submit']) && empty($errors) === true )
{
$name=basename($_FILES['foto']['name']);
$t_name=$_FILES['foto']['tmp_name'];
$dir='upload';
if(move_uploaded_file($t_name,$dir."/".$name))
{
}
else
{
}
}
?>

<?php
if(move_uploaded_file($t_name,$dir."/".$name))
{
mysql_connect('localhost','username','password');
mysql_select_db('yourdb');
$path=$dir."/".$name;
$sql="INSERT INTO `your_table`(`name`,`path`) values ('".$name."','".$path."')";
$result=mysql_query($sql);
if($result){
echo"Successfully added to db";
}
}
else
{
echo "Sorry.File Upload failed";
}
?>

Related

How do I add an image to a sql database

I am trying to insert a title, description and an image into an sql database, below is the form.
However, the code breaks after the form is submitted. I get redirected to the next page but none of the code in the next file gets processed.
It worked fine before I added the function to add an image and there was just text.
here is the code for the form that does not get processed correctly:
<?php
if (isset($_SESSION['username'])) {
echo "<form action='/origo/addnewtopic.php?cid=".$_GET['cid']."&scid=".$_GET['scid']."'
method='POST' enctype='multipart/form-data'>
<p>Titel: </p>
<input type='text' id='topic' name='topic' size='100' />
<p>Innehåll: </p>
<textarea id='content' name='content'></textarea><br />
<input type='file' name='image'>
<input type='submit' value='Lägg till' name='submit'/></form>"; ?>
And if anyone wonders, this is the file that it sends the info to that is trying to insert text and image to the database, but none of this gets processed.
<?php
session_start();
include ('dbconn.php');
$topic = addslashes($_POST['topic']);
$content = nl2br(addslashes($_POST['content']));
$image = ($_FILES['image']);
$cid = $_GET['cid'];
$scid = $_GET['scid'];
$insert = mysqli_query($con, "INSERT INTO topics (`category_id`, `subcategory_id`, `author`, `title`, `content`, `date_posted`)
VALUES ('".$cid."', '".$scid."', '".$_SESSION['username']."', '".$topic."', '".$content."', NOW());");
$tid = mysql_insert_id();
die($tid);
if($image) {
$insert2 = mysqli_query($con, "INSERT INTO images (`category_id`, `subcategory_id`, `topic_id`, `image`)
VALUES ('".$cid."', '".$scid."', '".$tid."', '".$image."');
}
else {
die("no image");
}
if ($insert) {
header("Location: /origo/topics.php?cid=".$cid."&scid=".$scid."");
} else {
die("error");
}
?>
try using blob datatype in the DB.
also here
$content = nl2br(addslashes($_POST['content']));
You must use $_FILES rather than $_POST. As the files like images are being stored in an array $_FILES that is later being extracted from. Also you must use file_get_contents for :
$content = nl2br(addslashes(file_get_contents($_POST['content'])));
Hope this helps a little
I have tried to insert image from database using php PDO. i have not save image directly i have store image path in my database. i am store in image path in my database.
<?php
//This is a database connection
$conn = new PDO("mysql:host=localhost; dbname=newdb;", 'root', '');
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<!-- This is a post type form it is a upload images -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="img" required /><br><br>
<button type="submit" name="submit-img">Store Image</button>
</form>
</body>
<html/>
<?php
if (isset($_POST['submit-img']))
{
$type = ['image/jpg', 'image/png', 'image/jpeg']; //Image type name
$img = $_FILES['img']; //Fetch files
if (in_array($img['type'], $type)) //Check file type is image or not
{
$file_tmp_name = $_FILES['img']['tmp_name'];
$file_name = $_FILES['img']['name'];
$folder = "images/".$file_name;
echo $folder;
if (move_uploaded_file($file_tmp_name, $folder)) //Upload image in folder
{
$sql = "INSERT INTO images (img) VALUES (?)";
$insert_img = $conn->prepare($sql);
if ($insert_img->execute([$file_name])) //This is a image path store in database
{
echo "<script>alert('image upload successfully...')</script>";
}
else
{
echo "Image cannot uploaded please try again";
}
}
else
{
echo "file cannot uploaded";
}
}
else
{
echo "<br>Please upload an image";
}
}
?>

The image cannot be displayed because it contains errors (php)

I would like to display an image stored in my database but I keep getting that error.
The image is stored in my database as longblob.
I upload it using this piece of code in upload.php:
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" />
<input type="submit" name="submit" value="UPLOAD" />
</form>
<?php
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check !== false) {
$image = $_FILES['image']['tmp_name'];
$imgContent = addslashes(file_get_contents($image));
/*
* Insert image data into database
*/
//Insert image content into database
$insert = $pdo->query("UPDATE users SET image='".$imgContent."'"."WHERE id_user = ".$posts[0]->get_id());
if ($insert) {
echo "File uploaded successfully.";
} else {
echo "File upload failed, please try again.";
}
} else {
echo "Please select an image file to upload.";
}
}
?>
Then I try to display it in getImage.php:
<?php
$id = $_GET['id'];
$query = $pdo->prepare('SELECT * FROM users WHERE username LIKE :us');
$query->bindValue(':us', $_SESSION['login'], PDO::PARAM_STR);
$query->execute();
$user = $query->fetchAll(PDO::FETCH_CLASS, "User");
header ('Content-Type: image/png');
echo $user[0]->get_image();
?>
When I go however to /getImage.php?id=1, I have the error
The image cannot be displayed because it contains errors
What am I doing wrong?
Solved: I added ob_end_clean(); before the header and it worked.

PHP Fail to upload image

test.php file
<?php
if(isset($_POST['submit']))
{
if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
{
echo "Please select an image";
}
else
{
$image = addslashes($_FILES['image']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
saveimage($image);
}
}
function saveimage($image)
{
$con=mysql_connect("localhost","root","");
mysql_select_db("food",$con);
$query = "INSERT INTO info(image) VALUES ('$image')";
$result = mysql_query($query,$con);
if($result)
{
echo "<br> Image upload";
}
else
{
echo "<br> NOT";
}
}
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("food",$con);
$query = "SELECT image from info";
$result = mysql_query($query,$con);
$row=mysql_fetch_array($result);
echo '<img src="data:image/jpeg;base64,'.$row["image"].'" width="200" height="200"/>';
}
?>
html file
<form method="post" action="test.php">
<label>Image:</label>
<input type="file" name="image"><br>
<input class="btn btn-primary" type="submit" name="submit" value="Confirm" style="height:50px; width:100px;">
<br><br>
</form>
Now i want to display the picture. But i keep getting a blank picture instead. Is there any problem with my display code there? Thanks
/dummy//aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa//dummy
add enctype="multipart/form-data" in your form
<form method="post" action="test.php" enctype="multipart/form-data">
Your are missing enctype="multipart/form-data" in your form tag.
The enctype attribute specifies how the form data should be encoded when submitting it to the server.
Note: The enctype attribute can be used only with method="post".
Add enctype="multipart/form-data" to your form tag.
you make a POST request, you have to encode the data that forms the body of the request.
When writing client-side code,you need to use multipart/form-data if your form includes any elements.

Data insert and Image Upload

I'm trying to Insert some data from a Text Area in MySQL and Upload an image in a specific folder and save the image name in MySQL. But when i submit it only text area data (titulli , permbjajtja) gets inserted in database, the picture doesn't get uploaded and name of the picture is not inserted in MySQL.
Here is the form code:
<form role="form" method="post" action="shtolajm1.php" enctype="multipart/form-data">
<div class="form-group">
<textarea class="form-control" rows="3" name="titulli"></textarea>
<textarea class="form-control" rows="10" name="permbajtja"></textarea>
<input type="file" name="files[]" style="margin-left:-5;"/>
<button type="submit" name="submit" class="btn btn-default" style="float:right;margin-top:10px;">Insert</button>
</div>
</form>
and here is the code that im using to insert the data to mysql and upload the picture:
if(isset($_POST['submit']))
{
if (!strlen(trim($_POST['titulli']))==0 && !strlen(trim($_POST['permbajtja']))==0 )
{
$titulli=$_POST['titulli'];
$permbajtja=$_POST['permbajtja'];
$data=date('Y-m-d');
$time=date('H:i');
$username=$_SESSION['myusername'];
$InsertQuerry="INSERT INTO lajme (titulli, permbajtja, data, ora, useri) VALUES ('$titulli','$permbajtja','$data','$time','$username')";
if (mysql_query($InsertQuerry))
{
echo "Data inserted";
}
}
else
{
echo "Type the title and container";
}
}
$id_lajmi=mysql_insert_id();
if(isset($_FILES['files']['name']))
{
for($i=0; $i<count($_FILES['files']['name']); $i++)
{
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
if ($tmpFilePath != "")
{
$path = "lajme_foto/";
list($txt, $ext) = explode(".", $name);
if(move_uploaded_file($_FILES['files']['tmp_name'][$i], $path.$id_lajmi."photo".$i.".".$ext))
{
$emri_fotos=$path.$id_lajmi."photo".$i.".".$ext;
$insertfoto="INSERT INTO lajme_foto (id_lajmi,emri_fotos) VALUES ('$id_lajmi','$emri_fotos')";
if(mysql_query($insertfoto))
{
echo "Image Inserted";
}
}
}
}
}
Can anyone help me solve this problem?
Thanks in advice.
You forgot to add enctype="multipart/form-data" to your form.
Your form tag should look like this:
<form role="form" method="post" action="shtolajm1.php" enctype="multipart/form-data">

Issue with updating image info on MYSQL database using PHP

I'm having problem with my code. I can't update my image.
Here is my full code:
index.php
//this link will post my data to next page
update
updatepage.php
//this page will get all data that want to update...
<?php
include("config.php");
$name=$_GET['code'];
$sql1 = "select * from imagename where name='$name'";
$result = mysql_query($sql1) or die(mysql_error());
$row=mysql_fetch_array($result);?>
<form name="form1" method="post" action="processupdatepage.php" class="formposition" enctype="multipart/form-data" >
<table>
<tr><td>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" /></td></tr>
<tr><td width="98">Image</td><td width="288">
//This is where I have problem, I can't get my image value but other data value work very well.....
<input type="file" name="image" value="<?php echo $row['image'];?>" /></td></tr><br/>
<tr><td>nane</td><td><input type="text" name="name" value="<?php echo $row['name']; ?>"/></td></tr><br/>
<tr><td></td> <td colspan="2">
<input type="submit" name="submit" value="Save" /> </td></tr>
</table>
</form>
OK. Now this my process file:
processupdatepage.php
<?php
include("config.php");
$id=$_POST['id'];
$image=$_FILES['image']['name'];
$name=$_POST['name'];
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
$query = "UPDATE imagename SET name='$name', image='$image' WHERE id='$id'";
$bb = mysql_query($query) or die(mysql_error());
if($bb)
{
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
$sql001="UPDATE imagename SET image='$image' WHERE image='$image'";
mysql_query($sql001);
} else { }
header("Location:index.php");
}
else
{
echo "Could not be updated";
}
?>
I can update BUT must select image. If I'm not selecting an image, my image field in database will be empty BUT other data updates are OK...
The value of an <input type="file"> cannot be programatically changed. Only by triggering its default behaviour that pops up the select file dialogue.
What I see from you example code is that you want to associate the value to the file form control element straight as it was retrieved from the database. So why saving the same back. Still, if you want to do this, you can use a hidden element with the value, that will be saved. But if you don't want the user to change it, just don't render it into the form and leave it out from your update query so it will remain unchanged.
Also, you could add some logic when you process the post and leave the field 'image' out of your update query if no file was selected.
I think the problem is here:
<input type="file" name="image" value="<?php echo $row['image'];?>" />
You can upload the image by clicking the browse button. so what do you trying to do like that?
If you want to show the image already uploaded you can use :
$img_path = 'get image path from database entry';
<img src= "<?php echo $img_path; ?>"/>
Here is full code to upload an Image, this is tested and works but you need to have a directory called 'upload' (this code does not create the folder).
It is advisable to only store image path on database.
<?php
if(isset($_POST['submit'])){
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}
else{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
// HERE YOU CAN WRITE YOU INSERT INTO MYSQL CODE
//SOMETHING LIKE THIS:
$path = 'assets/article_images/'.$article_id.'/'.$_FILES["image_file"]["name"];
$statement1 = "INSERT INTO image_article (article_id, image_path) values ('$article_id', '$path') ";
$query_result = mysql_query($statement1) or die($statement1."mysql error<br/><br/>".mysql_error());
if($query_result==1){
echo 'Image uploaded';
}
}
}
}
else
{
echo "Invalid file";
}
}
?>
<html>
<body>
<form action="index.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

Categories