I'm attempting to upload an image as well as add details such as; title, description and filepath into a database table.
I'm using the following code, but it isn't adding any data to the database;
(The session.php include contains the database connectivity.)
<?php include('includes/session.php');
$uploadDir = 'submitted/pictures/';
if(isset($_POST['submit']))
{
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading <strong>file</strong>";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$title = $_POST['title'];
$description = $_POST['description'];
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
mssql_query($query);
}
?>
The form code;
<form name="Image" enctype="multipart/form-data" action="upload-pics2.php" method="POST">
Title <input type="text" name="title" maxlength="100" class="textbox" value="<?php echo $form->value("title"); ?>" />
Description <textarea name="description" rows="8" cols="40" class="textbox" value="<?php echo $form->value("description"); ?>"></textarea>
File <input type="file" name="file" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26" class="textbox" />
<input type="submit" name="submit" value="Upload" class="button" />
</form>
I was wondering if someone could tell me what might be going wrong?
Thank you.
This code do not work because of several problems.
First, you should rename one of html fields or change field name when you are checking for upload:
<input type="submit" name="Upload" value="Upload" class="button" />
or
if(isset($_POST['submit']))
Second one, this script will not store any data into DB.
You should get, sanitize and write data into according fields, for example:
$title = mysql_real_escape_string($_POST['title']);
$description = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
You should make sure these fields present in DB, if not - you should create them:
ALTER table user_pictures ADD column description text, add column title varchar(255);
You has an error at this line if(isset($_POST['Upload']))
Change this to the if(isset($_POST['submit']))
is the 'submitted/pictures/' writable? also you might want to run is_uploaded_file() for an extra layer of security.
Also your query seems to be wrong
"INSERT INTO $user_pictures ( file ) VALUES ('$filePath')"
$user_pictures needs to be a table
try
"INSERT INTO `user_pictures` ( `file` ) VALUES ('$filePath')"
Related
I'm trying to upload an image of my HTML form into my MySQL blob column. the insertion is done successfully but the display of the image does not work properly knowing that images inserted directly into MySQL are displayed correctly.
HTML code:
<form class="form-horizontal" method='POST' action="add_question_submit.php" id="addQuestionForm" enctype="multipart/form-data">
<div class="form-group">
<textarea rows="4" cols="50" name="question" form="addQuestionForm" placeholder="Enter Question in brief.... " required></textarea><br>
<input type="file" class="form-control" id="image" name="image" required><br>
<input type="text" class="form-control" id="answer" placeholder="Enter Correct Answer" name="answer" required><br>
<input type="number" class="form-control" id="category_id" placeholder="Enter category id (only numeric)" name="category_id" required><br>
<input type="number" class="form-control" id="level_id" placeholder="Enter level id (only numeric)" name="level_id" required><br>
<input type="submit" name="submit" value="submit" class="btn btn-primary">
</div>
</form>
PHP code:
$file_temp = base64_encode( file_get_contents( $_FILES['image']['tmp_name'] ) );
$image = getimagesize($file_temp);
$query = "INSERT INTO questions(question_name, image, answer, category_id,level_id)VALUES('$question', '$image','$answer', '$category_id', '$level_id')";
$result = mysqli_query($conn, $query);
header("Location: display_question.php");
display_question.php :
<td><?php echo '<img src="data:image/png;base64,'.base64_encode($row['image']).'" />'; ?></br><br/></td>
Below is the function which will upload the images to specific folder.
You can all below function like:
Param 1: is the folder where we need to store the new image
Param 2: is FILES
Param 3: if any prefix for the image we need to pass it.
Param 4: if there is any previously uploaded image for same record. It should be deleted from the folder. Generally it is usefull when you are editing particluar record.
uploadfile("profile",$_FILES,"profile_pic");
Code is here:
function uploadfile($folder,$data,$preFix = "logo_",$previousImage="") {
$location = (pathinfo($_SERVER['SCRIPT_FILENAME']));
$uploads_dir = $location['dirname'] . "/assets/uploads/" . $folder . "/";
$fileNames = "";
$tmp_name = $data["tmp_name"];
$name = $data["name"];
$fileExtension = pathinfo($name, PATHINFO_EXTENSION);
$newfilename = $preFix . date("ymdhms") . '.' . $fileExtension;
$fulldest = $uploads_dir . $newfilename;
if (move_uploaded_file($tmp_name, $fulldest)) {
if($previousImage != "")
$this->removePreviousImage($folder, $previousImage); //deleting existing image
return $newfilename;
} else {
exit("Error File Uploading");
}
}
First you are storing the wrong information onto the database, you are storing the file size and not the encoded image.
$file_temp = base64_encode( file_get_contents( $_FILES['image']['tmp_name'] ) );
$image_size = getimagesize($file_temp);
$query = "INSERT INTO questions(question_name, image, answer, category_id,level_id)
VALUES('$question', '$file_temp','$answer', '$category_id', '$level_id')";
$result = mysqli_query($conn, $query);
header("Location: display_question.php");
Second, if you have stored the base64 encoded version of the file onto the database you do not need encode it again when you retrieve it from the database so your <img> tag should be
<?php echo "<img src='data:image/png;base64,$row[image]'/>"?>
</br><br/></td>
And thirdly and most importantly you need to be using parameterise bound queries to protect your app from SQL Injection Attack
$file_temp = base64_encode( file_get_contents( $_FILES['image']['tmp_name'] ) );
$image_size = getimagesize($file_temp);
$query = "INSERT INTO questions
(question_name, image, answer, category_id,level_id)
VALUES(?,?,?,?,?)";
$stmt = $conn->prepare($query);
$stmt->bind_params('sssss', $question,
$file_temp,
$answer,
$category_id,
$level_id);
$result = $stmt->execute();
if (!$result) {
echo $conn->error;
}
header("Location: display_question.php");
I want to upload an image to my server and save the image path to my database,
How can I rename the file to its auto-incrementing id? And save the path to DB
I mean if I have a file image.jpg. when I upload the image I want to rename it automatically to corresponding id.jpg (eg 1.jpg, 2.jpg 3.jpg etc ) and save that path to the database.
Here's the code I've now. But it's not working.
<?php
include 'db.php';
$title = $_POST['title'];
$description = $_POST['description'];
$lang = $_POST['lang'];
$fileName = $_FILES['file']['name'];
$target = "img/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["file"]["tmp_name"];
$result =
move_uploaded_file($tempFileName,$fileTarget);
$add = mysqli_query($conn,"INSERT INTO files(title,description,imgname,imgurl,date,lang) VALUES('$title','$description','$fileName',$fileTarget',CURDATE()),'$lang'");
if($add){
echo "File uploaded successfully";
}
else{
echo "Sorry upload failed.";
}
?>
Here's my form
<html>
<body>
<form name="upload" method="POST" action="upload.php" onsubmit="return validateform()" enctype="multipart/form-data">
<input type="text" name="title"><br>
<input type="text" name="description"><br>
<select name="lang">
<option value="Malayalam">Malayalam</option>
<option value="Tamil">Tamil</option>
<option value="Telugu">Telugu</option></select><br>
<input type="file" name="file">
<input type="submit" value="upload">
</form>
</body>
</html>
I think you have an issue with your insert query check here what the mistake I found...
$add = mysqli_query($conn,"INSERT INTO files(title,description,imgname,imgurl,date,lang) VALUES('$title','$description','$fileName','$fileTarget',CURDATE(),'$lang')");
There ')' is wrongly added near to CURDATE() and also a ' missed for $fileTarget and not well-ended insert query you create use above code for the same,
I want to insert some data to database by query in PHP. I have something like this.
$zp='INSERT INTO `user`(`name`, `password`, `avatar`) VALUES ("'.$_POST['login'].'","'.$_POST['password'].'")';
And i want to put in the third value
<img src="$file_name.$file_type"/>
But I have no idea how to write this in PHP query
You need to create an upload functionality, and to save only the path where you're images are stored.
Create a table in your database, with few column names: filepath, mime, size.
A little example: index.php:
if(isset($_FILES['file']['name'])){
$name = $_FILES['file']['name'];
$mime = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
$tmp = $_FILES['file']['tmp_name'];
$path = 'uploads/' . $name; //maybe you should create the uploads/ folder before running the script
if(move_uploaded_file($tmp, $path)){
$db = new PDO('mysql:host=localhost;dbname=your_db_name','your_db_user','your_db_pass');
$stmt = $db->prepare('INSERT INTO your_table_name_here SET filepath=?,mime=?,size=?');
$stmt->execute([$path,$mime,$size]);
echo 'File uploaded successfully!';
}
}
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
Then you can grab all the saved paths, and add them as src attrbuite for your images.
//index.php
$stmt = $db->prepare('SELECT filepath FROM your_table_name_here');
$stmt->execute();
while($row = $stmt->fetch()){?>
<img src="<?php echo $row['filepath']; ?>" alt="image">
<?php }
But notice this is just a super simple script, for your learning purposes, and this code must not be used in production mode, as is not safe.
I have this code for a form that uploads pictures to my website and saves the information to a mysql database:
<form method='post'>
Album Name: <input type="text" name="title" />
<input type="submit" name="submit" value="create" />
</form>
<h4>Add Photo</h4>
<form enctype="multipart/form-data" method="post">
<?php
require_once 'config.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(isset($_POST['upload'])){
$caption = $_POST['caption'];
$albumID = $_POST['album'];
$file = $_FILES ['file']['name'];
$file_type = $_FILES ['file']['type'];
$file_size = $_FILES ['file']['size'];
$file_tmp = $_FILES ['file']['tmp_name'];
$random_name = rand();
if(empty($file)){
echo "Please enter a file <br>";
} else{
move_uploaded_file($file_tmp, 'uploads/'.$random_name.'.jpg');
$ret = mysqli_prepare($mysqli, "INSERT INTO photos (caption, image_url, date_taken)
VALUES(?, ?, NOW())");
$filename = "uploads/" + $random_name + ".jpeg";
mysqli_stmt_bind_param($ret, "ss", $caption, $filename);
mysqli_stmt_execute($ret);
echo "Photo successfully uploaded!<br>";
}
}
?>
Caption: <br>
<input type="text" name="caption">
<br><br>
Select Album: <br>
<select name="album">
<?php
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$result = $mysqli->query("SELECT * FROM albums");
while ($row = $result->fetch_assoc()) {
$albumID = $row['albumID'];
$title = $row['title'];
echo "<option value='$albumID'>$title</option>";
}
?>
</select>
<br><br>
Select Photo: <br>
<input type="file" name="file">
<br><br>
<input type="submit" name="upload" value="Upload">
</form>
This successfully uploads the picture to my 'uploads' folder as well as my mysql database, however, I would like to put in image URL "uploads/(random name generated).jpg"
I have failed to do this with my current code, the information recorded in the 'image_url' column of my photos table is just the random number generated. without the "uploads/" in the beginning and ".jpg" in the end.
I should mention that the schema for my photos table is:
caption, image_url, date_taken, imageID
Any help will be very much appreciated!!
thank you in advance
You are using + (plus) signs to concatenate with, in this line:
$filename = "uploads/" + $random_name + ".jpeg";
PHP uses dots/periods to concatenate with, rather than plus signs which is JS/C language syntax:
$filename = "uploads/" . $random_name . ".jpeg";
Error checking would have signaled the syntax error.
I want to insert image path into database table so I can later display it on a different place but only thing that is getting inserted into the table is the folder name where pictures are uploaded into and the image name is missing.
Here is my code:
<?php
require "connect.php";
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
$uploaddir = 'uploaded';
if(isset($_POST['submit']))
{
$filename = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$filepath = $uploaddir . $filename;
move_uploaded_file($tmp,$filepath);
$filepath=addslashes($filepath);
mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$id'");
mysqli_close($conn);
}
?>
<div id="main">
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="upload"/>
</form>
</div>
Table column named imeslike is supposed to be updated with image path but it only shows uploaded/. It's like it does not accept variables when I put some random string in my query it gets updated and the string value shows up in the imeslike column.
The uploaded folder is in same directory so the relative path is OK and I also tried absolute path like:
$uploaddir="C:/wamp/www/admirovsajt/uploaded"
But same problem.
Verify that image was uploaded before looking for correct path in the database.
instead of:
$uploaddir = 'uploaded';
try
$uploaddir = 'uploaded/';
Try:
<?php
require "connect.php";
if(isset($_GET['id'])) {
echo $id = $_GET['id'];
}
$uploaddir = 'uploaded/';
if(isset($_POST['submit'])) {
$pid = $_POST['pid'];
$filename = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$filepath = $uploaddir . $filename;
move_uploaded_file($tmp,$filepath);
$filepath=addslashes($filepath);
mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$pid'");
mysqli_close($conn);
}
?>
<div id="main">
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="pid" value="<?php echo $id;?>">
<input type="file" name="image"/>
<input name="submit" type="submit" value="upload"/>
</form>
</div>