I am trying to save a image file name at database, but i cannot make it, please help me
my database have no wrong, duno why it cannot update to databse, but i can get the $newname correctly
?php session_start();
include_once("connectDB.php");
$ID = $_SESSION['ID'];
if(isset($_POST['upload'])){
$ID = $_SESSION['ID'];
$loc = "profilepicture/";
if($_FILES["Adminpic"]["type"] == "image/png" || $_FILES["Adminpic"]["type"] ==
"image/jpeg" || $_FILES["Adminpic"]["type"] == "image/jpg" || $_FILES["Adminpic"]
["type"] == "image/gif")
{
$ID = $_SESSION['ID'];
$file = explode(".", $_FILES["Adminpic"]["name"]);
$newname = "$ID.$file[0].$file[1]";
mysql_query("UPDATE admin SET Adminpic == '$newname' WHERE ID='$ID'");
$path = "$loc$newname";
move_uploaded_file($_FILES["Adminpic"]["tmp_name"], $path) ;
echo "Your image has been uploaded success, $newname";
}
else{
echo"invalid file.";
}
}
Because your query is incorrect
mysql_query("UPDATE admin SET Adminpic ='$newname' WHERE ID=$ID");
try with this because you use double equal after Adminpic .
Related
i'm having a small issue in the duplicated names.
I want to auto rename any duplicated upload files, like numbering them.
or if i could make the name same with numbers, such as file1.jpg / file2.jpg
for all uploaded files
here's my code
<?php
include('connect-db.php');
if (isset($_POST['submit'])) {
$filename= $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000))
{
if(file_exists($_FILES["imgfile"]["name"]))
{
echo "File name exists.";
}
else
{
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"photos/$filename");
}
}
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$id_photo= mysql_real_escape_string(htmlspecialchars($_POST['filename']));
// check that firstname/lastname fields are both filled in
if ($filename== '' ) {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
} else {
// save the data to the database
mysql_query("UPDATE table SET id_photo='$filename' WHERE id='$id' ") or die(mysql_error());
// once saved, redirect back to the view page
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
?>
Even the echo of if(file_exists($_FILES["imgfile"]["name"])) it's not working, i don't know why
Thank you very much before replying
try this code
this code will never get same name this code will rename file like 2jh5425h44u5h45h454k5image.jpg this is how it will save file so no need to worry about duplicate file
i have added random name generator $newname = md5(rand() * time()); this will generate random name for your file
<?php
include('connect-db.php');
$newname = md5(rand() * time());
if (isset($_POST['submit'])) {
$filename = $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif") || ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000)) {
if (file_exists($_FILES["imgfile"]["name"])) {
echo "File name exists.";
} else {
move_uploaded_file($_FILES["imgfile"]["tmp_name"], "photos/$newname . $filename");
}
}
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$id_photo = mysql_real_escape_string(htmlspecialchars($_POST['filename']));
// check that firstname/lastname fields are both filled in
if ($filename == '') {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
} else {
// save the data to the database
mysql_query("UPDATE table SET id_photo='$filename' WHERE id='$id' ") or die(mysql_error());
// once saved, redirect back to the view page
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
?>
if you need to rename only if file is duplicate here is answer Renaming duplicate files in a folder with php
I am facing a problem with send variable data to mysql, one of my variable is passing but other is not.
<?php
session_start();
if(!isset($_SESSION["PAT_ID"])){
ob_start();
header("location: login.php");
ob_end_flush();
}
$patient_id ="";
$complainID = "";
$patient_id = $_SESSION["PAT_ID"];
if(isset($_GET["ComplainID"])){
$complainID = $_GET["ComplainID"];
}
include "config/connect_to_mysql.php";
?>
<?php
//Diesease photo\
echo "Hello Patient Your Complain ID: " . $complainID;
$imageerr = "";
$typeerr = "";
$sizeerr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if( (isset($_FILES['galleryField_1']) && $_FILES['galleryField_1']['error'] == 0)
|| (isset($_FILES['galleryField_2']))
|| (isset($_FILES['galleryField_3']))
|| (isset($_FILES['galleryField_4']))
){
$allowedExts = array("JPEG", "jpeg", "jpg", "JPG");
$temp = explode(".", $_FILES["galleryField_1"]["name"]);
$extension = end($temp);
if ((
($_FILES["galleryField_1"]["type"] == "image/JPEG")
|| ($_FILES["galleryField_1"]["type"] == "image/jpeg")
|| ($_FILES["galleryField_1"]["type"] == "image/jpg")
|| ($_FILES["galleryField_1"]["type"] == "image/JPG"))
&& in_array($extension, $allowedExts)){
if($_FILES['galleryField_1']['size'] > 1048576) { //1 MB (size is also in bytes)
$sizeerr = "Photo must be within 1 MB";
} else{
// Add this image into the database now
$sql = mysql_query("INSERT INTO `shasthojito`.`sdispic` (`sdis_pic_id`, `pat_id`, `comp_id`) VALUES (NULL, '$patient_id', '$complainID')")
or die (mysql_error());
$gallery_id = mysql_insert_id();
// Place image in the folder
$newgallery = "$gallery_id.jpg";
move_uploaded_file( $_FILES['galleryField_1']['tmp_name'], "dpic/$newgallery");
}
}else{
$typeerr = "You have to put JPEG Image file";
}
}else{
$imageerr = "No Image Selected";
}
Here the variable $patientID is working fine and passing the data into it, but the $complainID is not working on sql query but its showing the value in echo ...
Your are mixing GET with POST Since you're using this line:
if ($_SERVER["REQUEST_METHOD"] == "POST")
You need to change this:
if(isset($_GET["ComplainID"])){
$complainID = $_GET["ComplainID"];
}
To:
if(isset($_POST["ComplainID"])){
$complainID = $_POST["ComplainID"];
}
Or maybe you only need to change this:
if ($_SERVER["REQUEST_METHOD"] == "POST")
To:
if ($_SERVER["REQUEST_METHOD"] == "GET")
Be sure about the method you are using to transfer date to your actual file.
EDIT 1:
Following your answers through your comments above, please change this:
$sql = mysql_query("INSERT INTO `shasthojito`.`sdispic` (`sdis_pic_id`, `pat_id`, `comp_id`) VALUES (NULL, '$patient_id', '$complainID')")
or die (mysql_error());
To:
$sql = mysql_query("INSERT INTO `shasthojito`.`sdispic` (`sdis_pic_id`, `pat_id`, `comp_id`) VALUES (NULL, '$patient_id', '".$complainID."')")
or die (mysql_error());
EDIT 2:
Before inserting the variable, be sure it is of the same type as the column comp_id of your table:
if (isset($_GET['ComplainID']) && ctype_digit($_GET['ComplainID']))
{
$complainID = $_GET["ComplainID"];
}
I have the bellow code which I was hoping to change/rename image name on upload to user id so I can avoid file overwrite and insert the name into database sadly after I added rename code the code is not able to upload image or update the database we out showing any error but if I remove the rename code everything was working.
Can one help me how to solve it or is there any better way I can do it?
<?php
$user_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$username = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
require("connection.php");
if(#$_POST ['submit']) {
$file = $_FILES ['file'];
$name1 = $file ['name'];
$type = $file ['type'];
$size = $file ['size'];
$tmppath = $file ['tmp_name'];
if($type == 'jpeg' || $type == 'png' || $type == 'jpg') {
$name1 = $user_id.$type; // rename image
if($name1!="") {
if(move_uploaded_file ($tmppath, 'users/'.$name1)) {
$sql=("INSERT INTO USERS set photo='$name1' WHERE username='$username'");
mysql_query ($sql) or die ('could not updated:'.mysql_error());
echo ("Profile picture updated");
}
}
}
}
?>
You can try this, may be help you ...
<?php
$user_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$username = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
require("connection.php");
if(#$_POST ['submit']) {
$file = $_FILES ['file'];
$name1 = time().$file ['name']; // rename image
$type = $file ['type'];
$size = $file ['size'];
$tmppath = $file ['tmp_name'];
if($type == 'image/jpeg' || $type == 'image/png' || $type == 'image/jpg') {
if($name1!="") {
if(move_uploaded_file ($tmppath, 'users/'.$name1)) {
$sql=("INSERT INTO USERS set photo='$name1' WHERE username='$username'");
mysql_query ($sql) or die ('could not updated:'.mysql_error());
echo ("Profile picture updated");
}
}
}
}}
?>
First of all change
$name1 = $user_id.$type;
to
$name1 = $user_id.".".$type;
And second of all clean up you sql.
Also. file_type is image/jpeg so that's why it doesn't work. It never goes past your if.
Create a switch to check the filetype or just take the last 3 characters of the file.
Try this to reorganise your $_FILES into an array you can understand and easily work with.
Shameless plug
https://gist.github.com/lukeoliff/5531772#file-quickrearrangefiles-php
<?php
function rearrangeFiles($arr) {
foreach($arr as $key => $all){
foreach($all as $i => $val){
$new[$i][$key] = $val;
}
}
return $new;
}
Used as such:
<?php
$user_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$username = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
require("connection.php");
if(!empty($_POST) && !empty($_FILES)) {
$files = rearrangeFiles($_FILES)
foreach ($files as $key => $file) {
$name = $file['name'];
$type = $file['type'];
$size = $file['size'];
$tmppath = $file['tmp_name'];
if($type == 'jpeg' || $type == 'png' || $type == 'jpg') {
$name = time() . '_' . $user_id.'_'.$name.'.'.$type; // TIMESTAMP, USERID and FILENAME RENAME
if(!empty($name)) {
if(move_uploaded_file($tmppath, 'users/'.$name)) {
$sql = "INSERT INTO users (photo,username) values ('$name','$username')";
mysql_query($sql) or die('could not updated:'.mysql_error());
$successes[] = $file['name'] . " picture saved as " . $name;
}
}
}
}
if (!empty($successes)) {
echo implode('. ',$successes);
}
}
Further improved by inserting into database in a single query :) Also you really need to move from mysql_ functions to mysqli_ or PDO:: functions as per php.net http://www.php.net/manual/en/function.mysql-connect.php depreciating mysql_ functions soon.
you can use that one concept, but edit this as your requirement.
<?php
if ($_FILES['imagepath']['name'] != "")
{
$uploaddir = 'images/';
$uploadfile = $uploaddir . basename($_FILES['imagepath']['name']);
if (move_uploaded_file($_FILES['imagepath']['tmp_name'], $uploadfile))
{
$rename = $_FILES['imagepath']['name'];
$rename = rand(0,1500000000).$rename;
$filename = strtolower(($rename));
if (file_exists(($uploaddir.$_FILES['imagepath']['name'])))
rename(($uploaddir.$_FILES['imagepath']['name']), ($uploaddir.$filename));
echo $_FILES['imagepath']['name']." with name ".$filename." file uploaded successfully";
}
}
?>
i am uploading some data to the db that contain title, news date and image, but when i want to update it i am facing problems.what i want to do basically if i update all the row except image then updation do not take place. what i want basically when i have to update lets suppose title only then it should update it but all other data should remain same but problem is that i have to select image again from my pc in updation. my scenario is that i just save the name in db not the whole path and hard code the path where ever i need to display the image
here is html
<div class="row">
<label>Image upload</label>
<div class="right"><input type="file" name="file" value="<?php echo $row['images'];?>" /></div>
</div>
here is php
if(($_GET['mod']=='edit') && (isset($_POST['hidden'])))
{
echo $_FILES["file"]["name"];
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $images));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo $_FILES["file"]["error"] . "<br>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload-images/" . $images);
$update="UPDATE headline SET
headline_title = '$title',
headline_des = '$description',
month = '$month_name',
day = '$day_name',
year = '$year_name',
featured = '$featured',
headline = '$headline',
images = '$images'
where id = ".$_GET['id']."";
$result = mysql_query($update);
}
}
Submitting the form again will cause the new value of the file input which will be empty
so you have to check if it's empty or not and act according to the status
For example
if($_FILES['file']['name'] != "")
{
//upload the image with what ever you want
//move_uploaded_file($_FILES['file']['tmp_name'],$target.$image );
//the SQL query should contain the updating the image column
if(($_GET['mod']=='edit') && (isset($_POST['hidden'])))
{
echo $_FILES["file"]["name"];
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $images));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo $_FILES["file"]["error"] . "<br>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload-images/" . $images);
$update="UPDATE headline SET
headline_title = '$title',
headline_des = '$description',
month = '$month_name',
day = '$day_name',
year = '$year_name',
featured = '$featured',
headline = '$headline',
images = '$images'
where id = ".$_GET['id']."";
$result = mysql_query($update);
}
}
}
else
{
//SQL update without image
$update="UPDATE headline SET
headline_title = '$title',
headline_des = '$description',
month = '$month_name',
day = '$day_name',
year = '$year_name',
featured = '$featured',
headline = '$headline'
WHERE id = ".$_GET['id']."";
$result = mysql_query($update);
}
if you don't want the image to be edited simply you can remove it from the update and the form used for that or but it's path in hidden input
Hope this will help
According to your comment the query should look something like this
$update="UPDATE headline SET
headline_title = '$title',
headline_des = '$description',
month = '$month_name',
day = '$day_name',
year = '$year_name',
featured = '$featured',
headline = '$headline'
WHERE id = ".$_GET['id']."";
$result = mysql_query($update);
I think you need to use good intending to make your code more readable and maintainable in the future :)
Solution
check the file is not empty: if(!empty($_FILES['fileToUpload']['name']))
Take update query with mentioning image column in your table in IF statement,
if images not uploaded, then it will upload.
Take update query without mentioning image column in your table in ELSE statement,if file is empty, it will upload
CONCLUSION
Next time when you update any other field the image won't get disappeared, meaning file path wont be empty in your database, and if already present it won't change unless you manually change it..
i am trying to allow users to update their profile picture using this code.
require("../connection.php");
$imgName = $_FILES['pic']['name'];
$imgTmp = $_FILES['pic']['tmp_name'];
$imgtype = $_FILES['pic']['type'];
$imgSize = $_FILES['pic']['size'];
$maxFileSize = 200000;
$pic = "../uploads/" . $user_id . "_" . time() . $imgName;
if ($imgSize > $maxFileSize) {
$error = "size";
}
if ($imgType == "image/jpeg" || $imgType == "image/gif") {
$error .= "";
} else {
$error = "type";
}
if (file_exists($pic)) {
$error = "exists";
}
if ($error == "" && $imgName != "") {
move_uploaded_file($imgTmp, $pic);
mysql_query("UPDATE users SET pic = '$pic', WHERE username = '$username'");
if (!mysql_query($query, $connect)) {
die(mysql_error());
} else {
mysql_close($connect);
header('location:http://www.WEBSITE.co.uk/users/upload-pic-thanks.php');
}
} else {
header("Location:edit-pic-error.php?e=".$error);
}
and it gives me this in the address bar: edit-pic-error.php?e=type, however the file i am trying to upload is .jpg, and its smaller than the 20000kb allowance.
The table in my mysql database is called 'users', and the table row is called 'pic', its Varchar, 60, allow null ticked.
The table is not being updated with the new time stamped profile picture.
Please help.
Thanks very much
$imgtype = $_FILES['pic']['type'];
if ($imgType == "image/jpeg" || $imgType == "image/gif") {
$imgType vs. $imgtype, notice the case.