I am trying to upload my pic into folder and file link store into database although file store in folder but unfortunately doesn't store link in database. Please see where I am doing mistake.
<?php
include('dbconnection.php');
if(count($_FILES["file"]["name"]) > 0)
{
sleep(3);
for($count=0; $count<count($_FILES["file"]["name"]); $count++)
{
$file_name = $_FILES["file"]["name"][$count];
$tmp_name = $_FILES["file"]['tmp_name'][$count];
$file_array = explode(".", $file_name);
$file_extension = end($file_array);
if(file_already_uploaded($file_name, $connect))
{
$file_name = $file_array[0] . '-'. rand() . '.' . $file_extension;
}
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$stmt= $connect->prepare("INSERT INTO tbl_image (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $file_name);
$stmt->execute();
}
}
}
function file_already_uploaded($file_name, $connect)
{
$statement = $connect->prepare("SELECT image_name FROM tbl_image WHERE image_name = '".$file_name."'");
$statement->execute();
$number_of_rows = $statement->rowCount();
if($number_of_rows > 0)
{
return true;
}
else
{
return false;
}
}
?>
store the image name as location with file name:
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$stmt= $connect->prepare("INSERT INTO tbl_image (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $location.'/'.$file_name);
$stmt->execute();
}
Related
I am trying to save a picture into my database along with the path file. But what it does now is incorrect. It only saves the image into the database and not the entire image path. What's wrong?
I do the exact same thing with this code in another project and can't wrap my head around the problem here.
$userPic = '';
$date_time = date('Y-m-d_H-i-s');
if(!empty($userLoggedIn)) {
if (isset($_FILES['fileToUpload'])) {
$errors = array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size = $_FILES['fileToUpload']['size'];
$width = 1500;
$height = 1500;
$file_tmp = $_FILES['fileToUpload']['tmp_name'];
$file_type = $_FILES['fileToUpload']['type'];
$tmp = explode('.', $_FILES['fileToUpload']['name']);
$file_ext = strtolower (end ($tmp));
$extensions = array("jpeg", "jpg", "png", "gif");
if(in_array($file_ext, $extensions) === false) {
$errors[] = "extension not allowed. Please choose a JPEG or PNG file.";
}
if ($file_size > 8097152) {
$errors[] = 'File size must be 2 MB';
}
if ($width > 1500 || $height > 1500) {
echo"File is to large";
}
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp, "assets/images/profile_pics/" . $userPic);
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $userPic, $username);
$stmt->execute();
$stmt->close();
}
}
}
else {
echo "Invalid Username";
}
You can assign another variable that contains both the path and the variable for the image you used, and then use that variable in your query:
$file_path = "assets/images/profile_pics/".$userPic;
Your code:
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp,"assets/images/profile_pics/" . $userPic);
$imag_path = "assets/images/profile_pics/" . $userPic;
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $imag_path, $username);
$stmt->execute();
$stmt->close();
}
Try this:
You save only the new image name, not path.
Upload file not working on server but it is working on localhost. File upload permission is ON, but even getting error. I tried all the solution over internet.
Here is my code.
if($submit == "UPLOAD PROFILE PICTURE") {
$user = $_COOKIE['userId'];
$file_name = $_FILES['userPic']['name'];
$file_size =$_FILES['userPic']['size'];
$file_tmp =$_FILES['userPic']['tmp_name'];
$file_type=$_FILES['userPic']['type'];
$tmp = explode('.', $file_name);
$file_ext = end($tmp);
$expensions= array("jpeg","jpg","png");
$nameToStore = $user.".".$file_ext;
chmod("images/users-dp/$nameToStore",0777);
if(in_array($file_ext,$expensions)=== true){
if($file_size < 2097152){
if(move_uploaded_file($file_tmp,"images/users-dp/".$nameToStore)) {
$queryFoCheck = "SELECT * FROM profilepic WHERE user = '$user'";
$resultFoCheck = $connection -> query($queryFoCheck);
$countFoCheck = mysqli_num_rows($resultFoCheck);
if($countFoCheck>=1) {
$query = "UPDATE profilepic SET piclink = '$nameToStore' WHERE user = '$user'";
$result = $connection -> query($query);
} else {
$query = "INSERT INTO profilepic VALUES ('$user', '$nameToStore') ";
$result = $connection -> query($query);
}
header('Location: profile.php?s'); //successsfully updated
} else {
header('Location: profile.php?e=1'); //Cant update
}
} else {
header('Location: profile.php?e=2'); //Cant update
}
} else {
header('Location: profile.php?e=3'); //Cant update
}
}
I try to understand how to use multiple uploads in PDO.
So I have my post.php:
$database = new Database();
$db = $database->getConnection();
$media = new Media($db);
if($_POST){
$image = !empty($_FILES["image"]["name"]) ? sha1_file($_FILES['image']['tmp_name']) . "-" . time() . "-" . basename($_FILES["image"]["name"]) : "";
$media->image = $image;
if ($media->create()) {
echo $media->uploadPhoto();
$_POST=array();
}
}
<input name="image[]" type="file" />
And my media.php with pdo query and some upload validations:
public $image;
public $created;
public function create(){
//write query
$query = "INSERT INTO " . $this->table_name . "
SET image=:image,
created=:created";
$stmt = $this->conn->prepare($query);
$this->image=htmlspecialchars(strip_tags($this->image));
$stmt->bindParam(":image", $this->image);
if($stmt->execute()){
return true;
}
print_r($stmt->errorInfo());
return false;
}
function uploadPhoto(){
$result_message="";
if(!empty($_FILES["image"]["tmp_name"])){
$target_directory = "../uploads/";
$target_file = $target_directory . $this->image;
$file_type = pathinfo($target_file, PATHINFO_EXTENSION);
$file_upload_error_messages="";
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check!==false){
}else{
$file_upload_error_messages.="<div></div>";
}
$allowed_file_types=array("jpg", "JPG", "jpeg", "JPEG", "png", "PNG", "gif", "GIF");
if(!in_array($file_type, $allowed_file_types)){
$file_upload_error_messages.="<div></div>";
}
if(file_exists($target_file)){
}
if($_FILES['image']['size'] > (10485760)){
$file_upload_error_messages.="<div></div>";
}
if(!is_dir($target_directory)){
mkdir($target_directory, 0777, true);
}
if(empty($file_upload_error_messages)){
if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)){
}else{
$result_message.="<div></div>";
}
}
else{
$result_message.="{$file_upload_error_messages}";
}
}
return $result_message;
}
So I need to store the values in different mysql records and upload them all to the server.
What is the best way to do this and where to place the foreach?
I struggle with the right place of the foreach ...
$x=0;
foreach ( $_FILES['image']['name'] AS $key => $value ){
// ...
$x++;
}
so if this is your foreach loop and you want to insert different records for each uploaded file then use mysqli_multi_query
$x=0;
$query = "";
foreach ( $_FILES['image']['name'] AS $key => $value ){
$query .= 'insert into tableName (col1,col2,col3,image)VALUES("a","b","c","'.$value.'");';
$x++;
}
$query = rtrim($query,";");
mysqli_multi_query($connectionObj,$query);
Your query will look somthing like this
insert into tableName (col1,col2,col3,image)VALUES("a","b","c","a.jpg");
insert into tableName (col1,col2,col3,image)VALUES("a","b","c","b.jpg");
I'm trying to make a loop which checks if an image with filename from database exists, if not to unlink all images because I have many duplicates in folder but folder is 50gb. I can't check each one.
So here's what I've tried
$id = $_GET['id'];
$sql = "SELECT thumbnail FROM files WHERE id='$id'";
$query = $mysqli->query($sql);
$row = $query->fetch_assoc();
$thumb = $row['thumbnail'];
$records = "../upload/images/";
foreach ($records as $record) {
if (file_exists('../upload/images/'.$thumb)) {}
else {
#unlink('../upload/images/'.$thumb);
}
}
Update
$sql = "SELECT thumbnail FROM filesWHERE id='$id'";
$query = $mysqli->query($sql);
$row = $query->fetchAll();
foreach($sql as $search_result) {
if(file_exists($search_result['thumbnail'])) {
$img_source = ('../upload/images/'.$search_result['thumbnail']);
} else {
#unlink('../upload/images/'.$search_result);
}
}
That's the logic I've understood. Checking if there are files in the folder that aren't present in database, and if so, delete it.
$directory = "../upload/images/";
$images = glob($directory . "*.jpg");
foreach($images as $image)
{
$sql = "SELECT thumbnail FROM files WHERE thumbnail =?";
$stmt = $mysqli->prepare($sql);
if($stmt) {
$stmt->bind_param('s', $image);
$stmt->bind_result($result);
$stmt->execute();
$stmt->fetch();
if(!$result) {
if(unlink($image)) {
echo "Image deleted $image <br>\n";
}
}
} else {
echo "Unable to prepare SQL";
}
}
This code is to update database. it updates everything even uploads image sucessfully but after image upload the whole page gets blank and only "Array()" is displayed at top. Why is that?
<?php
if(!isset($_GET["prid"])){
header("Location: prjedit.php");
}
else {
$prid = intval($_GET["prid"]);
$sqlprj = "SELECT * FROM projects WHERE id = ? LIMIT 1";
$statement = $db->prepare($sqlprj);
$statement->execute(array($prid));
$project = $statement->fetchObject();
//submitted form
if( (isset($_POST["title"])) && (isset($_POST["details"])) ) {
$title = $_POST['title'];
$desc = $_POST['descr'];
$details = $_POST['details'];
if(!empty($_FILES['image']['name'])) {
//update image
$file = basename($_FILES['image']['name']);
$dir = "projects/";
$target_path = $dir . basename($_FILES['image']['name']);
$tempname = $_FILES['image']['tmp_name'];
if(!file_exists($target_path)) {
if(move_uploaded_file($tempname, $target_path)) {
$sqlimg = "UPDATE projects SET image = ? WHERE id = ?";
$statement = $db->prepare($sqlimg);
$statement->execute(array($file, $prid));
if($statement->rowCount() > 0) {
try {
chdir('./projects/');
unlink($project->image);
chdir('..');
}
catch (Exception $e) {
$message = "Sorry image delete failed ";
echo $e->getMessage();
}
}
else {
die ($db->errorInfo());
}
}
else {
$message = "Sorry Image update failed";
}
}
else {
$message = "Sorry this image already exists but text";
}
}
// update project texts
$sqlupd = "UPDATE projects SET title = ?, descinfo = ?, details = ? WHERE id = ?";
$statement = $db->prepare($sqlupd);
$statement->execute(array($title, $desc, $details, $prid));
if($statement->rowCount()) {
$message = " Saved successfully";
}
else {
die($db->errorInfo());
}
}
}
?>
Looking at Pdo::codeInfo documentation, it returns an array.
When you write die($db->errorInfo()); it will try to display this array.
As suggested by the documentation itself, you could try print_r($db->errorInfo()); die; and see what happens.