updated values are displaying only after refreshing the page - php

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();
}

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
}

PHP - broken image displaying from database

Every time a user submits a picture for their "profile pic" it will display as a "broken image" and I noticed that when I physically insert an image into the mysql data base and display it, it works perfectly and the size of the file changes to "BLOB - KiB" instead of MB. But when I insert that same image into the database using my "upload file", that image turns to "BLOB MB" and doesn't display on the website. I saw some post about this and they said to remove the "addslashes" from the variable and i did that but it still didn't work. So what i wan't to do is display the image from the database that was submitted by the user. It works when you physically insert it into the database without a file but if you do it with one, it doesn't work. Here is a screen shot of the database structure, upload file, and retrieving file.
PHP Upload file
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post') { //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['username'])) {
if($_SESSION['came_from_upload'] != true) {
setcookie("username", "", time() - 60 * 60);
$_COOKIE['username'] = "";
header("Location: developerLogin.php");
exit;
}
error_reporting(E_ALL & ~E_NOTICE);
if($_SERVER['REQUEST_METHOD'] == "POST") {
$token = $_SESSION['token'];
$userid = $_SESSION['id'];
$fullname = addslashes(trim($_POST['fullname']));
$username = addslashes(trim($_POST['username']));
$email = addslashes(trim($_POST['email']));
$password = addslashes(trim($_POST['password']));
$storePassword = password_hash($password, PASSWORD_BCRYPT, array(
'cost' => 10
));
$file_tmp = addslashes(trim($_FILES['file']['tmp_name']));
$file_name = addslashes(trim($_FILES['file']['name']));
try {
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
die("There was an error connecting to the database");
}
$stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = ?");
$stmtChecker->execute(array(
$userid
));
if($result = !$stmtChecker->fetch()) {
setcookie("username", "", time() - 60 * 60);
$_COOKIE['username'] = "";
header("Location: developerLogin.php");
exit;
}
if(!empty($fullname)) {
$stmtFullname = $handler->prepare("UPDATE generalusersdata SET fullname = ? WHERE user_id = ?");
$stmtFullname->execute(array(
$fullname,
$userid
));
}
if(!empty($username)) {
$stmtCheckerUsername = $handler->prepare("SELECT * FROM generalusersdata WHERE username = ?");
$stmtCheckerUsername->execute($username);
if($resultCheckerUsername = $stmtCheckerUsername->fetch()) {
die("Username Already in use! Please try again");
}
$stmtUsername = $handler->prepare("UPDATE generalusersdata SET username = ? WHERE user_id = ?");
$stmtUsername->execute(array(
$username,
$userid
));
}
if(!empty($email)) {
if(filter_var($email, FILTER_VALIDATE_EMAIL) == false) {
die("Email is Not Valid!");
}
$stmtCheckerEmail = $handler->prepare("SELECT * FROM generalusersdata WHERE email = ?");
$stmtCheckerEmail->execute($email);
if($resultCheckerEmail = $stmtCheckerEmail->fetch()) {
die("Email Already in use! Please try again");
}
$stmtEmail = $handler->prepare("UPDATE generalusersdata SET email = ? WHERE user_id = ?");
$stmtEmail->execute(array(
$email,
$userid
));
}
if(!empty($password)) {
if(strlen($password) < 6) {
die("Password has to be GREATER than 6 characters!");
}
//Check if password has atleast ONE Uppercase, One Lowercase and a number
if(!preg_match("(^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$)", $password)) {
echo 'Password needs to be at least ONE uppercase, ONE lowercase, and a number!';
exit;
}
$stmtPassword = $handler->prepare("UPDATE generalusersdata SET password = ? WHERE user_id = ?");
$stmtPassword->execute(array(
$storePassword,
$userid
));
}
if($_FILES['file']['error'] == UPLOAD_ERR_OK) {
$mime = mime_content_type($_FILES['file']['tmp_name']);
if(strstr($mime, "video/")) {
die("Please note that this file is NOT an image... Please select an image for your Profile Picture");
} else if(strstr($mime, "image/")) {
$allowedTypes = array(
IMAGETYPE_PNG,
IMAGETYPE_JPEG
);
$detectedType = exif_imagetype($_FILES['file']['tmp_name']);
if($extensionCheck = !in_array($detectedType, $allowedTypes)) {
die("Failed to upload image; the format is not supported");
}
$dir = "devFiles/";
$uploadedFile = $dir . basename($_FILES['file']['name']);
if(is_dir($dir) == false) {
mkdir($dir, 0700);
}
if(!move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFile)) {
die("There was an error moving the file... Please try again later!");
}
$stmtFile = $handler->prepare("UPDATE generalusersdata SET profile_image = ?, file_tmp = ? WHERE user_id = ?");
$stmtFile->execute(array(
$file_name,
$file_tmp,
$userid
));
}
}
$_SESSION['token'] = $token;
header("Location: developerUpload.php");
exit;
}
} else {
header("Location: developerLogin.php");
exit;
}
HTML
<form method="post" enctype="multipart/form-data" autocomplete="off">
Information Changer<br>
Fullname: <input type="text" name="fullname" placeholder="Full Name.....">
<br/>
<br/>
Username: <input type="text" name="username" placeholder="User Name.....">
<br/>
<br/>
Email: <input type="text" name="email" placeholder="Email.....">
<br/>
<br/>
Password: <label><input type="password" name="password" placeholder="Password....." ></label>
<br></br>
Profile Picture: <input type="file" name="file">
<br/>
<input type="submit" name="submit">
</form>
Retrieving file
try {
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
die("There was an error connecting to the database");
}
$stmt = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = :userid");
$stmt->bindValue(':userid', '61', PDO::PARAM_INT);
$stmt->execute();
while($result = $stmt->fetch()) {
echo '<img src="data:image/jpeg;base64,' . base64_encode($result['file_tmp']) . '"/>';
}
You are storing the temporay filename - not its contents.
$file_tmp = addslashes(trim($_FILES['file']['tmp_name']));
Should be
$file_tmp = file_get_contents($_FILES['file']['tmp_name']);

My 'move_uploaded_file()' does not move my image to my specified folder

<?php
include("config.php");
//Get the name of the input type submit
if(ISSET($_POST['sign_up'])) {
$username = trim($_POST['user']);
$password = trim($_POST['pass']);
$gender=$_POST['gen'];
$firstname =($_POST['first']);
$lastname = trim($_POST['last']);
$y=$_POST['y'];
$m=$_POST['m'];
$d=$_POST['d'];
$dob=$y."-".$m."-".$d;
$imgpath=$_FILES['file']['name'];
$imgFile = $_FILES['file']['name'];
$tmp_dir = $_FILES['file']['tmp_name'];
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userpic = rand(1000,1000000).".".$imgExt;
if(!empty($username) && !empty($password)) {
$sql = mysql_query("SELECT * FROM users WHERE user_name = '$username'") or die(mysql_error());
if(mysql_num_rows($sql) > 0) {
$msg_error = "Username already registered!";
} else {
if(in_array($imgExt, $valid_extensions)){
mysql_query("INSERT INTO users
values('','$username','".MD5($password)."', '$gender',
'$dob', '$imgpath', 'guest',
'$firstname', '$lastname')")
or die(mysql_error());
$uuid=mysql_query("SELECT * FROM users");
while ($puid=mysql_fetch_array($uuid)){
$pid = $puid['user_id'];
mkdir("userImages/$pid");
move_uploaded_file($_FILES["file"]["tmp_name"], "userImages/$pid/" . $_FILES["file"]["name"]);
}
//image uploaded should be moved to my specified
//folder after the code above is executed
$_SESSION['sname']=$_POST['user'];
$msg_success = "You are now registered!";
}
else{
$msg_error = "Invalid image!";
}
}
}else{
$msg_error = "All fields are required!";
}
}
?>
this is my php code. Can someone help me in figuring out why my 'move_uploaded_file()' is not working?
Check your destination folder permissions. error_get_last could give you some clue to why it doesn't work. Check this example
$targetFile = "userImages/$pid/" . $_FILES["file"]["name"];
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
echo "<P>FILE UPLOADED TO: $target_file</P>";
} else {
echo "<P>MOVE UPLOADED FILE FAILED!</P>";
print_r(error_get_last());
}

updating table in mysql

hi im planning to update my sql database by using these line of codes
<?php
//session_start();
$user=$_SESSION['user_level'];
// Check if a file has been uploaded
if(isset($_FILES['fileToUpload'])) {
// Make sure the file was sent without errors
if($_FILES['fileToUpload']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('$host', '$user', '$pass',
'$tbl_name');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
//$id= mysql_insert_id();
$name = $dbLink->real_escape_string($_FILES['fileToUpload']['name']);
$mime = $dbLink->real_escape_string($_FILES['fileToUpload']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['fileToUpload']
['tmp_name']));
$size = intval($_FILES['fileToUpload']['size']);
// Create the SQL query
$query = "
UPDATE userinfo SET resume=$name
WHERE FirstName=$user";
// Execute the query
$result = $dbLink->query($query);}}
?>
<?php
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload/" . $_FILES["fileToUpload"]["name"]);
?>
<?php
if ($_FILES["fileToUpload"]["error"] > 0)
{
echo "Apologies, an error has occurred.";
echo "Error Code: " . $_FILES["fileToUpload"]["error"];
}
else
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload/" . $_FILES["fileToUpload"]["name"]);
}
if (($_FILES["fileToUpload"]["type"] == "image/DOC")
|| ($_FILES["fileToUpload"]["type"] == "image/jpeg")
|| ($_FILES["fileToUpload"]["type"] == "image/png" )
&& ($_FILES["fileToUpload"]["size"] < 10000))
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload/" . $_FILES["fileToUpload"]["name"]);
ECHO "Files Uploaded Succesfully";
echo'<script type="text/javascript">
window.location.href ="resume2.php"
</script>';
}
else
{
}
echo "Your Resume was Successfully Upload";
?>
the problem is it doesn't work. my column for resume doesn't change. am i missing something? because it doesn't display any error. thank you in advance!
You just use the following the line
$query = "UPDATE userinfo SET resume='$name' WHERE FirstName='$user'";
instead of
$query = "UPDATE userinfo SET resume=$name WHERE FirstName=$user";
just try it. It may works
Try with the following :
PHP Part :
<?php
$host = 'Your Host Name';
$user = 'Your Database Username';
$pass = 'Your Database Password';
$db_name = 'Your Database Name';
$first_name = 'john';//Here your session user firstname
//Check if a file has been uploaded
if(isset($_FILES['fileToUpload'])) {
// Connect to the database
$dbLink = new mysqli(''.$host.'', ''.$user.'', ''.$pass.'',''.$db_name.'');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($dbLink->connect_error) {
die('Connect Error (' . $dbLink->connect_errno . ') '. $dbLink->connect_error);
}
$name = $_FILES['fileToUpload']['name'];
$mime = $_FILES['fileToUpload']['type'];
$temp_name = $_FILES['fileToUpload']['tmp_name'];
$size = intval($_FILES['fileToUpload']['size']);
$first_name = $_POST['first_name'];
if(($_FILES["fileToUpload"]["type"] == "image/DOC") || ($_FILES["fileToUpload"]["type"] == "image/jpeg") || ($_FILES["fileToUpload"]["type"] == "image/png" ) && ($_FILES["fileToUpload"]["size"] < 10000)) {
// Create the SQL query
$query = "UPDATE `userinfo` SET `resume`='$name' WHERE `FirstName`='$first_name'";
// Execute the query
$result = $dbLink->query($query);
move_uploaded_file($temp_name,"gallery3/".$name);
echo "Files Uploaded Succesfully";
}
else {
echo "Apologies, an error has occurred.";
echo "Error Code: " . $_FILES["fileToUpload"]["error"];
}
}
?>
HTML Part :
<form action="" method="post" enctype="multipart/form-data" name="fileupload">
<input type="file" name="fileToUpload">
<input type="hidden" name="first_name" value="<?php echo $first_name;?>">
<input type="submit" name="uploading" value="File Upload">
</form>
I think this may help you to resolve your problem.

Categories