How to Declare timestamp as variable and convert to ddmmyy format - php

I have a date issue here. I have a timestamp field in mysql table called filedate. However I have tried several times to declare it and also convert it to a dd-mm-yy format. Unfortunately when I load it the date is still in timestamp format and when I then upload it claims I haven't declared the variable filedate.
Any assistance pointing me in the right direction would be gratefully accepted.
All the code is below. I also have a HTML file to show upload and description.
if (isset($_POST['action']) and $_POST['action'] == 'upload')
{
// Bail out if the file isn't really an upload
if (!is_uploaded_file($_FILES['upload']['tmp_name']))
{
$error = 'There was no file uploaded!';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
$uploadfile = $_FILES['upload']['tmp_name'];
$uploadname = $_FILES['upload']['name'];
$uploadtype = $_FILES['upload']['type'];
$uploaddesc = $_POST['desc'];
$uploaddata = file_get_contents($uploadfile);
$filedate = time();
include 'db.inc.php';
// Prepare user-submitted values for safe database insert
$uploadname = mysqli_real_escape_string($link, $uploadname);
$uploadtype = mysqli_real_escape_string($link, $uploadtype);
$uploaddesc = mysqli_real_escape_string($link, $uploaddesc);
$uploaddata = mysqli_real_escape_string($link, $uploaddata);
$sql = "INSERT INTO filestore SET
filename = '$uploadname',
mimetype = '$uploadtype',
description = '$uploaddesc',
filedata = '$uploaddata'";
if (!mysqli_query($link, $sql))
{
$error = 'Database error storing file!';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
if (isset($_GET['action']) and
($_GET['action'] == 'view' or $_GET['action'] == 'download') and
isset($_GET['id']))
{
include 'db.inc.php';
$id = mysqli_real_escape_string($link, $_GET['id']);
$sql = "SELECT filename, mimetype, filedata, DATE_FORMAT(STR_TO_DATE( filedate, '%d-%b-%Y'), '%Y.%m.%d')
FROM filestore
WHERE id = '$id'";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Database error fetching requested file.';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
$file = mysqli_fetch_array($result);
if (!$file)
{
$error = 'File with specified ID not found in the database!';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
$filename = $file['filename'];
$mimetype = $file['mimetype'];
$filedata = $file['filedata'];
$disposition = 'inline';
if ($_GET['action'] == 'download')
{
$mimetype = 'application/octet-stream';
$disposition = 'attachment';
}
// Content-type must come before Content-disposition
header("Content-type: $mimetype");
header("Content-disposition: $disposition; filename=$filename");
header('Content-length: ' . strlen($filedata));
echo $filedata;
exit();
}
if (isset($_POST['action']) and $_POST['action'] == 'delete' and
isset($_POST['id']))
{
include 'db.inc.php';
$id = mysqli_real_escape_string($link, $_POST['id']);
$sql = "DELETE FROM filestore
WHERE id = '$id'";
if (!mysqli_query($link, $sql))
{
$error = 'Database error deleting requested file.';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
include 'db.inc.php';
$sql = 'SELECT id, filename, mimetype, description, filedate
FROM filestore';
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Database error fetching stored files.';
include $_SERVER['DOCUMENT_ROOT'] . 'mediamouse/includes/error.html.php';
exit();
}
$files = array();
while ($row = mysqli_fetch_array($result))
{
$files[] = array(
'id' => $row['id'],
'filename' => $row['filename'],
'mimetype' => $row['mimetype'],
'description' => $row['description'],
'filedate' => $row['filedate']);
}
include 'files3.html.php';
?>

Use NOW() when inserting. When formatting, I don't think you need to parse the TIMESTAMP typed column, as DATE_FORMAT should be able to work with timestamps directly.
This works:
SELECT DATE_FORMAT( CURRENT_TIMESTAMP( ) , '%Y.%m.%d' )

you have to use UNIX_TIMESTAMP() in your select statement

Related

Displaying images from Database not working

I have tried a number of methods but my code still doesn't show images from the database on my website. When I click upload, I get an output of only the file name and file details but no photos are shown.
Here is my code that has to display the images.
<main>
<section align='center'>
<h1 id="rcorner2"align='center'style="font-size:30px; position:fixed;">Photo Library</h1>
<br><br>
<div class="wrapper">
<!--h2 align='left'>Photos</h2-->
<div class="photo-container">
<?php
include_once 'dbh.php';
$sql = "SELECT * FROM photos ORDER BY orderPhotos DESC";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "Error updating photo library!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div style="background-image: url(../libraries/photos/'.$row["imageFullName"].');"></div>
<h3>'.$row["filetitle"].'</h3>
<p>'.$row["filedescription"].'</p>
</a>';
}
}
?>
</div>
</div>
</section>
</main>
Connection to database
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portal uploads";
$conn = mysqli_connect($servername, $username, $password, $dbname);
?>
And here is the database connection from the html form.
<?php
if(isset($_POST['upload'])) {
$newFileName = $_POST['filename'];
if(empty($newFileName)){
$newFileName = "photo";
}else{
//Replacing spaces in filename with underscores
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$filetitle = $_POST['filetitle'];
$filedescription = $_POST['filedescription'];
$file = $_FILES['file'];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
//Error handling for allowed file types
if(in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if($fileSize < 10000000) {
//Make file unique through naming
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "../libraries/photos/" . $imageFullName;
include_once "dbh.php";
//Checking for error handling when fields have been left empty
if(empty($filetitle) || empty($filedescription)) {
header("location:photos_edit.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM photos;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setPhotoOrder = $rowCount + 1;
$sql = "INSERT INTO photos (filetitle, filedescription, imageFullName, orderPhotos) VALUES (?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
}else{
mysqli_stmt_bind_param($stmt, "ssss", $filetitle, $filedescription, $imageFullName, $setPhotoOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("location: photos_edit.php?upload=success");
}
}
}
}else{
echo "Photo is too big!";
exit();
}
}else{
echo "An error ocurred while uploading your image!";
exit();
}
}else{
echo "File type not supported";
exit();
}
}
?>
For example, if you use this code, you can load an image from DB (MySQL) :)
<?php
$connection =mysql_connect("localhost", "root" , "");
$sqlimage = "SELECT * FROM userdetail where `id` = '".$id1."'";
$imageresult1 = mysql_query($sqlimage,$connection);
while($rows = mysql_fetch_assoc($imageresult1))
{
echo'<img height="300" width="300" src="data:image;base64,'.$rows['image'].'">';
}
?>

Image Removed while updating other record in php mysqli

While updating the record if I do not upload the image and click on update button the current image will be removed.
Here is the code
<?php
if (isset($_POST['update_record'])){
$edit_id = $_GET['edit'];
$username = $_POST['name'];
$email = $_POST['email'];
$city = $_POST['city'];
$file_name = $_FILES['file']['name'];
$file_tmp_name = $_FILES['file']['tmp_name'];
$file_error = $_FILES['file']['error'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$allowed = ['png' , 'jpg' , 'jpeg'];
$pathinfo = pathinfo($file_name , PATHINFO_EXTENSION);
$destination = "uploads/" . $file_name ;
if (in_array($pathinfo , $allowed)){
if ($file_size < 100000){
if ($file_error === 0){
move_uploaded_file($file_tmp_name, $destination) ;
} //error close here
else{
echo "Some kind of error";
}
} //size close here
else{
echo "File Size is too big!";
}
} //type close here
else{
echo "File type is wronng";
}
$update_query = "UPDATE crud
SET `name`='$username' , `email`='$email' ,
`city`='$city', `image`='$destination'
WHERE id=$edit_id";
$run = mysqli_query($connect, $update_query) ;
if ($run){
header("Location: show_record.php") ;
} else{
echo "Error in Updating the data";
}
} //main if isset close here
?>
verify that a file exists before proceeding. if no file exist, then DO NOT update the $destination in your update query
//use a flag
$fileExists = false;
if(!empty($_FILES['file'])) { //check here
$fileExists = true;
//rest of the file upload code
}
if($fileExists === true){
// a file was uploaded. now update $destination variable in update query as well
}

updated values are displaying only after refreshing the page

i am trying to update name ,email , image informations in form.
name, email was updating fine, but image was not saving in folder, so i removed ; in below line :
if ($user_home->update($uname,$email, $phone, $uid)); ,
now once we click on "save" button, images are saving in folders,
but name & emails are displaying old values, & after refreshing page displaying updated values. but i want to display updated values once we click on save button.
form
<form action="profile.php" method="POST" enctype="multipart/form-data">
Name :
<?php echo $row['userName'] ?> <br/>
Email :
<?php echo $row['userEmail'] ?> <br>
<h3>photo</h3>
<input type="file" name="photo" id="fileSelect"><br>
<input type="submit" name="submit" value="Save" />
</form>
code for name ,email
<?php
include 'home.php';
// session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$phone = $_POST['phone'];
$uid = (isset($_GET['userID']) ? intval($_GET['userID']) : -1);
// query
if ($user_home->update($uname,$email, $phone, $uid)); // This is the line
{
header("Location: profile.php");
die();
}
}
?>
code for image
<?php
if(isset($_FILES["photo"]["error"])){
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "Error: Invalid parameters - please contact your server administrator.";
}
?>
You need to do the select query after the update query, otherwise you are getting the old info and then update the record in the database.
<?php
include 'home.php';
// session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$phone = $_POST['phone'];
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
// query
if ($uid > 0 && $user_home->update($uname,$email, $phone, $uid)) // This is the line
{
header("Location: profile.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
Or you can use this custom update:
// query
if ($uid > 0)
{
$stmt = $user_home->runQuery("UPDATE tbl_users SET userName=:uname,
userEmail=:email, phone=:phone WHERE userID=:uid");
$stmt->execute(array(
":uid"=>$_SESSION['userSession'],
":email" => $email,
":phone" => $phone,
":uname" => $uname
));
header("Location: profile.php");
die();
}

alternate to upload image or not

I am new in stackoverflow and in PHP too, so I want to describe my problem first. Sorry if I have bad grammar, I am not native though.
I make a form that let user post (to database) with or without an image, this the code
$link = mysqli_connect('localhost', 'root', '12345!##', 'pklapps') or die("Couldnt connect to the server");
//public info dari admin
if (isset($_POST["title"]) && isset($_POST["content"]) && isset($_POST["category"])) {
$title = $_POST['title'];
$desc = $_POST['content'];
$lat = $_POST['latitude'];
$long = $_POST['longitude'];
$category = $_POST['category'];
$image = $_POST['userfile'];
if (!isset($_FILES['userfile'])) {
$query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
$result = mysqli_query($link, $query);
if ($result) {
header('Location: post.php?success');
} else {
header('Location: post.php?error');
}
} else {
$fileName = $_FILES['userfile']['name'];
$target = "uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["userfile"]["tmp_name"];
$result = move_uploaded_file($tempFileName,$fileTarget);
/*
* If file was successfully uploaded in the destination folder
*/
if ($result) {
header('Location: post.php?success');
$query = "INSERT INTO public_info (title, content, category, imagePath) VALUES ('$title','$desc','$category', '$fileTarget')";
$link->query($query) or die("Error : ".mysqli_error($link));
} else {
header('Location: post.php?errimg');
}
mysqli_close($link);
}
}
and the form goes normal when i attach the image or file but it goes to header('Location: post.php?errimg'); when i not attach the image. Please help me with this, thank you.
Replace your if condition from !isset($_FILES['userfile']) to empty($_FILES['userfile']['name'])
//if (!isset($_POST[]))
$title = $_POST['title'];
$desc = $_POST['content'];
$lat = $_POST['latitude'];
$long = $_POST['longitude'];
$category = $_POST['category'];
$image = $_POST['userfile'];
if(empty($_FILES['userfile']['name'])) {
$query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
$result = mysqli_query($link, $query);
if ($result) {
header('Location: post.php?success');
}
else {
header('Location: post.php?error');
}
}
else {
$fileName = $_FILES['userfile']['name'];
$target = "uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["userfile"]["tmp_name"];
$result = move_uploaded_file($tempFileName,$fileTarget);
/*
* If file was successfully uploaded in the destination folder
*/
if($result) {
header('Location: post.php?success');
$query = "INSERT INTO public_info (title, content, category, imagePath) VALUES ('$title','$desc','$category', '$fileTarget')";
$link->query($query) or die("Error : ".mysqli_error($link));
}
else {
header('Location: post.php?errimg');
}
mysqli_close($link);
}
// $query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
} ?>

PHP upload in database and folder in my root folder

So I'm trying to upload the file name of the image in the database and the image itself will be save in the folder inside a root folder.
In my codes, the image name is able to be saved in the database but the image itself did not save in the folder. Why is that?
Here's my code:
<?php
include '../session.php';
require_once 'config.php';
if (isset($_POST['submit'])) {
$img_dir = "updated_photo/";
$target_file = $img_dir . basename($_FILES["image"]["name"]);
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = $_FILES["image"]["type"];
if (substr($imageType, 0,5) == "image") {
$query = "UPDATE `crew_info` SET `image_name` = ? WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'si', $imageName, $_POST['id']);
mysqli_stmt_execute($stmt);
$id = $_POST['id'];
header("Location: ../admin/view_all_info.php?id=$id");
}
else {
echo "Image not Uploaded!";
}
}
?>
What seems to be the problem of my codes?
You just get the contain of file. forget to put in target folder use file_put_contents
$target_file = $img_dir . basename($_FILES["image"]["name"]);
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
// Write the contents back to the file
file_put_contents($target_file, $imageData);
You can also use move_uploaded_file to uploaded file to a new location
Here try this, I edited your codes.
<?php
include '../session.php';
require_once 'config.php';
if (isset($_POST['submit'])) {
$img_dir = "../updated_photo/";
$target_file = $img_dir . basename($_FILES["image"]["name"]);
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = $_FILES["image"]["type"];
if (substr($imageType, 0,5) == "image") {
$query = "UPDATE `crew_info` SET `image_name` = ? WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'si', $imageName, $_POST['id']);
mysqli_stmt_execute($stmt);
file_put_contents($target_file, $imageData);
$id = $_POST['id'];
header("Location: ../admin/view_all_info.php?id=$id");
}
else {
echo "Image not Uploaded!";
}
}
?>
just copy and paste it. tell if it worked.
<?php
include '../session.php';
require_once 'config.php';
if (isset($_POST['submit'])) {
$img_dir = "updated_photo/";
$target_file = $img_dir . basename($_FILES["image"]["name"]);
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = $_FILES["image"]["type"];
if (substr($imageType, 0,5) == "image") {
$query = "UPDATE `crew_info` SET `image_name` = ? WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'si', $imageName, $_POST['id']);
mysqli_stmt_execute($stmt);
$id = $_POST['id'];
//remove
if (file_exists($target_file))
{
$result = unlink($target_file);
if (!$result)
{
//error, display error,
return false;
}
}
//upload
$result = move_uploaded_file($_FILES['image']['tmp_name'], $img_dir);
if(!$result)
{
//error upload
}
header("Location: ../admin/view_all_info.php?id=$id");
}
else {
echo "Image not Uploaded!";
}
}
?>
try

Categories