updating table in mysql - php

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.

Related

How to fix Upload image using php and mysqli

I tried replacing mysql to mysqli, but I encountered an error in this code, it worked on mysql before. What is wrong?
Php:
<?php include "../../../_includes/config.php"; ?>
<?php
session_start();
if(!empty($_FILES['userAvatar']['name'])){
$uploadedFile = "";
if(!empty($_FILES["userAvatar"]["type"])){
$filename = $_FILES['userAvatar']['name'];
$valid_extensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["userAvatar"]["name"]);
$file_extension = end($temporary);
if((($_FILES["userAvatar"]["type"] == "image/png") || ($_FILES["userAvatar"]["type"] == "image/jpg") || ($_FILES["userAvatar"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
$sourcePath = $_FILES['userAvatar']['tmp_name'];
$targetPath = "../../../uploads/image/".$filename;
if(move_uploaded_file($sourcePath, $targetPath)){
$uploadedFile = $filename;
}
}
}
$display_name = $_POST['display_name'];
$biography = $_POST['biography'];
$sql = mysqli_query($connect, "UPDATE tb_users SET userDisplayName = '$display_name', userBiography = '$biography', userAvatar = '$uploadedFile' WHERE userLogin = '".$_SESSION['is_logged_in']['userLogin']."'") or die(mysqli_error());
if($sql){
echo "ok";
}else{
echo "err";
}
}else{
echo "err";
}
?>
Result always "err".
try this code:-
$sql = mysqli_query($connect, "UPDATE tb_users SET userDisplayName = '$display_name', userBiography = '$biography', userAvatar = '$uploadedFile' WHERE userLogin = '".$_SESSION['is_logged_in']['userLogin']."'") or die(mysqli_error($connect));
// no need of this
if($sql){
echo "ok";
}else{
echo "err";
}
Try this code below
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'your db';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
session_start();
if(!empty($_FILES['userAvatar']['name'])){
$uploadedFile = "";
if(!empty($_FILES["userAvatar"]["type"])){
$filename = $_FILES['userAvatar']['name'];
$valid_extensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["userAvatar"]["name"]);
$file_extension = end($temporary);
if((($_FILES["userAvatar"]["type"] == "image/png") || ($_FILES["userAvatar"]["type"] == "image/jpg") || ($_FILES["userAvatar"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
$sourcePath = $_FILES['userAvatar']['tmp_name'];
$targetPath = "../../../uploads/image/".$filename;
if(move_uploaded_file($sourcePath, $targetPath)){
$uploadedFile = $filename;
}
}
}
$display_name = $_POST['display_name'];
$biography = $_POST['biography'];
$sql ="UPDATE tb_users SET userDisplayName = '$display_name', userBiography = '$biography', userAvatar = '$uploadedFile' WHERE userLogin = '".$_SESSION['is_logged_in']['userLogin']."'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
}else{
//echo "err";
}
?>

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']);

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

Uploading image and form to database

So, i've been wondering for this script and still can't get it right. For some reason it won't save to my database. Any ideas why it's not working? Would appreciate any help. Thanks! Here's my script.
<?php
include_once ("database.php"); ?>
<?php
if (isset($_POST['anisave'])) {
$id = $_POST['id'];
$title = $_POST['title'];
$genre = $_POST['genre'];
$description = $_POST['description'];
$start = $_POST['start'];
$stop = $_POST['stop'];
$image_file = $_FILES['image']['name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
if (empty($image_file) || empty($id)) {
echo "Sorry, form is not complete yet!";
header('Location: add.php');
}
else{
$query_id = mysql_query("SELECT * FROM anidata WHERE id = '$id'");
$check = mysql_num_rows($query_id);
if ($check > 0) {
echo "Sorry, Anime ID not available";
header('Location: add.php');
}
else{
if ($type != "image/gif" && $type != "image/jpg" && $type != "image/jpeg" && $type != "image/png") {
echo "Invalid image file, please use JPEG,JPG,PNG or GIF to upload the image."
header('Location: add.php');
}
if ($size > 10000) {
echo "Affordable file is under 10mB."
header('Location: add.php');
}
else{
$upload_directory = 'upload/';
$temp = $upload_directory.$image_file;
if (move_uploaded_file($_FILES['image']['tmp_name'] , $temp)) {
$sql = "INSERT INTO anidata VALUES ('$id', '$title', '$temp', '$genre', '$description','$start', '$stop')";
$query = mysql_query($sql)
if ($query) {
header('Location: view.php');
}
else{
echo mysql_query();
}
}
else{
echo "<p> Upload Failed, error code = " . $_FILES['location']['error']. "</p>";
}
}
}
}
}
else{
unset($_POST['anisave']);
}
?>

Mysqli not importing letters

I am trying to make a sign up PHP for my website and I am trying to convert an old script that used mysql to mysqli. I am having a problem where that when I type any letters (abc) into any of the text fields the data is not imported into the database. If I use numbers (123) in all of the boxs it works and gets imported fine. I have tried mixing it up with some letters for the username and numbers for the password to see if only one text box was causing the problem but ANY box that have a letter in will cause the script not to work.
This is my PHP script:
<?php
$mysqli = new mysqli("localhost","root","","users_db");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Define username */
if(isset($_POST['username'])){
$username = $_POST['username'];
}
/* Define email */
if(isset($_POST['email'])){
$email = $_POST['email'];
}
/* Define password */
if(isset($_POST['password'])){
$password = $_POST['password'];
}
/* Define cpassword */
if(isset($_POST['cpassword'])){
$cpassword = $_POST['cpassword'];
}
if (trim($username) == ''){
echo 'No username entered.';
exit();
}
if (strlen($username) <= 5 || strlen($username) >= 30){
echo 'Username needs to be between 5 and 30 characters';
exit();
}
if (trim($email) == ''){
echo 'No email entered.';
exit();
}
if (trim($password) == ''){
echo 'Invalid password.';
exit();
}
if ($password != $cpassword){
echo 'Passwords do not match';
exit();
}
$run = mysqli_query($mysqli, "SELECT * FROM users WHERE username='$username'");
if (mysqli_num_rows($run)>0){
echo 'Username already exists';
exit();
}
$import = "INSERT INTO users (username,email,password) VALUES ($username,$email,$password)";
if (mysqli_query($mysqli, $import)){
echo 'Registration Successful';
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
$id = $row['id'];
mkdir("../users/" . $id, 0777, true);
fopen("../users/" . $id . "/" . "New User.txt", "w") or die("Unable to create file");
}else{
echo 'Failed to import';
}
?>
I am very new to PHP and mysqli so don't be too harsh if I am doing something stupid :)
Thanks Fred -ii- putting quotes around ($username,$email,$password) worked for me and now everything works. I will also fix the other problems suggested above.

Categories