Newbie - If image field empty use current profile picture - PHP - php

Good day, I am writing a PHP page to update a user's profile details, such as first name, last name, email address mobile number and a profile picture. Everything works fine, I can update a profile picture and store the file name and extension in the database and display it wherever I want to.
BUT
Let's say today I update my profile picture.
Let's say tomorrow I want to change only one detail (MY NAME)
When you update only one detail, I think the file input is empty.
Is there a way to use the value already existing in the database for the profile picture instead of updating an empty field???
<?php echo htmlentities($result->image);?>
PHP CODE:
<?php
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])==0)
{
header('location:login.php');
}
else{
if(isset($_POST['submit']))
{
$file = rand(1000,100000)."-".$_FILES['image']['name'];
$file_loc = $_FILES['image']['tmp_name'];
$file_size = $_FILES['image']['size'];
$file_type = $_FILES['image']['type'];
$folder="assets/images/user-pp/";
/* new file size in KB */
$new_size = $file_size/1024;
/* new file size in KB */
/* make file name in lower case */
$new_file_name = strtolower($file);
/* make file name in lower case */
$final_file=str_replace(' ','-',$new_file_name);
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$mobile=$_POST['mobile'];
$idedit=$_POST['editid'];
$image=$_POST['image'];
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$image=$final_file;
}
$sql="UPDATE users SET firstname=(:firstname), lastname=(:lastname), email=(:email), mobile=(:mobile), Image=(:image) WHERE id=(:idedit)";
$query = $dbh->prepare($sql);
$query-> bindParam(':firstname', $firstname, PDO::PARAM_STR);
$query-> bindParam(':lastname', $lastname, PDO::PARAM_STR);
$query-> bindParam(':email', $email, PDO::PARAM_STR);
$query-> bindParam(':mobile', $mobile, PDO::PARAM_STR);
$query-> bindParam(':image', $image, PDO::PARAM_STR);
$query-> bindParam(':idedit', $idedit, PDO::PARAM_STR);
$query->execute();
$msg="Information Updated Successfully";
}
?>
HTML FORM
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="media">
<a href="javascript: void(0);">
<img src="assets/images/user-pp/<?php echo htmlentities($result->image);?>" class="rounded mr-75" alt="profile image" height="64" width="64"></a>
<div class="media-body mt-75">
<div class="col-12 px-0 d-flex flex-sm-row flex-column justify-content-start">
<label class="btn btn-sm btn-primary ml-50 mb-50 mb-sm-0 cursor-pointer" for="account-upload">Upload new photo</label>
<input type="file" name="image" id="account-upload" class="form-control" hidden>
<input type="hidden" class="form-control" value="<?php echo htmlentities($result->image);?>">
<button class="btn btn-sm btn-outline-warning ml-50">Reset</button>
</div>
<p class="text-muted ml-75 mt-50"><small>Allowed JPG, GIF or PNG. Max size of 800kB</small></p>
</div>
</div>
<div class="col-12">
<div class="form-group">
<div class="controls">
<label for="account-username">First Name</label>
<input type="text" name="firstname" class="form-control" id="firstname" placeholder="First Name" value="<?php echo htmlentities($result->firstname);?>" required data-validation-required-message="Your first name is required!">
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<div class="controls">
<label for="account-username">Last Name</label>
<input type="text" name="lastname" class="form-control" id="lastname" placeholder="Last Name" value="<?php echo htmlentities($result->lastname);?>" required data-validation-required-message="Your last name is required!">
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<div class="controls">
<label for="account-name">Email</label>
<input type="email" name="email" class="form-control" id="email" placeholder="Email" value="<?php echo htmlentities($result->email);?>" required data-validation-required-message="Your email address is required!">
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<div class="controls">
<label for="account-e-mail">Mobile</label>
<input type="tel" name="mobile" class="form-control" id="mobile" placeholder="Mobile" value="<?php echo htmlentities($result->mobile);?>" required data-validation-required-message="Your mobile number is required!">
</div>
</div>
</div>
<input type="hidden" name="editid" class="form-control" required value="<?php echo htmlentities($result->id);?>">
<?php
if($error){?>
<h5 class="danger">
<?php echo htmlentities($error); ?>
</h5>
<?php }
else if($msg){?>
<h5 class="success">
<?php echo htmlentities($msg); ?>
</h5>
<?php } ?>
<div class="col-12 d-flex flex-sm-row flex-column justify-content-end">
<button type="submit" name="submit" class="btn btn-primary mr-sm-1 mb-1 mb-sm-0">Save
changes</button>
<button type="reset" class="btn btn-outline-warning">Cancel</button>
</div>
</div>
</form>

Try the code bellow and see if this solves what you are trying to achieve:
<?php
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])==0) {
header('location:login.php');
}
function fileUpload() {
if (!empty($_FILES)) {
$file = rand(1000,100000)."-".$_FILES['image']['name'];
$file_loc = $_FILES['image']['tmp_name'];
$file_size = $_FILES['image']['size'];
$file_type = $_FILES['image']['type'];
$folder = "assets/images/user-pp/";
/* new file size in KB */
$new_size = $file_size/1024;
/* new file size in KB */
/* make file name in lower case */
$new_file_name = strtolower($file);
/* make file name in lower case */
$final_file = str_replace(' ','-',$new_file_name);
try {
//throw exception if can't move the file
if (!move_uploaded_file($file_loc, $folder.$final_file)) {
throw new Exception('Could not move file');
}
return $final_file;
} catch (Exception $e) {
die ('File did not upload: ' . $e->getMessage());
}
}
return "";
}
if(isset($_POST['submit'])) {
$firstname = !empty($_POST['firstname']) ? $_POST['firstname'] : '';
$lastname = !empty($_POST['lastname']) ? $_POST['lastname'] : '';
$email = !empty($_POST['email']) ? $_POST['email'] : '';
$mobile = !empty($_POST['mobile']) ? $_POST['mobile'] : '';
$idedit = !empty($_POST['idedit']) ? $_POST['idedit'] : '';
$image = fileUpload();
try {
$sql = "UPDATE users SET ";
if($firstname != '') { $sql .= "firstname=(:firstname)"; }
if($lastname != '') { $sql .= ", lastname=(:lastname)"; }
if($email != '') { $sql .= ", email=(:email)"; }
if($mobile != '') { $sql .= ", mobile=(:mobile)"; }
if($image != '') { $sql .= ", Image=(:image)"; }
if($idedit != '') { $sql .= " WHERE id=(:idedit)"; }
$query = $dbh->prepare($sql);
if($firstname != '') { $query-> bindParam(':firstname', $firstname, PDO::PARAM_STR); }
if($lastname != '') { $query-> bindParam(':lastname', $lastname, PDO::PARAM_STR); }
if($email != '') { $query-> bindParam(':email', $email, PDO::PARAM_STR); }
if($mobile != '') { $query-> bindParam(':mobile', $mobile, PDO::PARAM_STR); }
if($image != '') { $query-> bindParam(':image', $image, PDO::PARAM_STR); }
if($idedit != '') { $query-> bindParam(':idedit', $idedit, PDO::PARAM_STR); }
$query->execute();
$msg="Information Updated Successfully";
} catch (Exception $e) {
/* if something fails inside try block will be catched here */
print $e->getMessage();
}
}
?>

So the solution was basic, but it took some hard thinking, LOL, for someone who has only been dabbling with code for two months;)
Instead of trying to set a default value for the file input field, rather set the php/mysql at the top of the form page to check
is the file size bigger than 0?
if so, then update all fields including profile picture / avatar / file
(else)
update only specified other fields
HERE IS HOW
php at the top of page
-<?php
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])==0)
{
header('location:login.php');
}
else{
if(isset($_POST[submit]))
{
if($_FILES['image']['size'] > 0)
{
$file = $_FILES['image']['name'];
$file_loc = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$folder="assets/images/user-pp/";
/* make file name in lower case */
$new_file_name = strtolower($file);
/* make file name in lower case */
$final_file=str_replace(' ','-',$new_file_name);
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$mobile=$_POST['mobile'];
$idedit=$_POST['editid'];
$image=$_POST['image'];
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$image=$final_file;
}
$sql="UPDATE users SET firstname=(:firstname), lastname=(:lastname), email=(:email), mobile=(:mobile), Image=(:image) WHERE id=(:idedit)";
$query = $dbh->prepare($sql);
$query-> bindParam(':firstname', $firstname, PDO::PARAM_STR);
$query-> bindParam(':lastname', $lastname, PDO::PARAM_STR);
$query-> bindParam(':email', $email, PDO::PARAM_STR);
$query-> bindParam(':mobile', $mobile, PDO::PARAM_STR);
$query-> bindParam(':image', $image, PDO::PARAM_STR);
$query-> bindParam(':idedit', $idedit, PDO::PARAM_STR);
$query->execute();
$msg="Information Updated Successfully";
}
else {
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$mobile=$_POST['mobile'];
$idedit=$_POST['editid'];
$sql="UPDATE users SET firstname=(:firstname), lastname=(:lastname), email=(:email), mobile=(:mobile) WHERE id=(:idedit)";
$query = $dbh->prepare($sql);
$query-> bindParam(':firstname', $firstname, PDO::PARAM_STR);
$query-> bindParam(':lastname', $lastname, PDO::PARAM_STR);
$query-> bindParam(':email', $email, PDO::PARAM_STR);
$query-> bindParam(':mobile', $mobile, PDO::PARAM_STR);
$query-> bindParam(':idedit', $idedit, PDO::PARAM_STR);
$query->execute();
$msg="Information Updated Successfully";
}
}
?>
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="media">
<a href="javascript: void(0);">
<img src="assets/images/user-pp/<?php echo htmlentities($result->image);?>" class="rounded mr-75" alt="profile image" height="64" width="64"></a>
<div class="media-body mt-75">
<div class="col-12 px-0 d-flex flex-sm-row flex-column justify-content-start">
<label class="btn btn-sm btn-primary ml-50 mb-50 mb-sm-0 cursor-pointer" for="account-upload">Upload new photo</label>
<input type="file" name="image" id="account-upload" class="form-control" hidden>
<button class="btn btn-sm btn-outline-warning ml-50">Reset</button>
</div>
<p class="text-muted ml-75 mt-50"><small>Allowed JPG, GIF or PNG. Max size of 800kB</small></p>
</div>
</div>
<div class="col-12">
<div class="form-group">
<div class="controls">
<label for="account-username">First Name</label>
<input type="text" name="firstname" class="form-control" id="firstname" placeholder="First Name" value="<?php echo htmlentities($result->firstname);?>" required data-validation-required-message="Your first name is required!">
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<div class="controls">
<label for="account-username">Last Name</label>
<input type="text" name="lastname" class="form-control" id="lastname" placeholder="Last Name" value="<?php echo htmlentities($result->lastname);?>" required data-validation-required-message="Your last name is required!">
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<div class="controls">
<label for="account-name">Email</label>
<input type="email" name="email" class="form-control" id="email" placeholder="Email" value="<?php echo htmlentities($result->email);?>" required data-validation-required-message="Your email address is required!">
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<div class="controls">
<label for="account-e-mail">Mobile</label>
<input type="tel" name="mobile" class="form-control" id="mobile" placeholder="Mobile" value="<?php echo htmlentities($result->mobile);?>" required data-validation-required-message="Your mobile number is required!">
</div>
</div>
</div>
<input type="hidden" name="editid" class="form-control" required value="<?php echo htmlentities($result->id);?>">
<?php
if($error){?>
<div class="col-12">
<div class="alert alert-warning alert-dismissible mb-2" role="alert">
<button type="button" class="close" data-dismiss="danger" aria-label="Close"><span aria-hidden="true">×</span></button>
<p class="mb-0">
<?php echo htmlentities($error); ?>
</p>
</div>
</div>
<?php }
else if($msg){?>
<div class="col-12">
<div class="alert alert-success alert-dismissible mb-2" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<p class="mb-0">
<?php echo htmlentities($msg); ?>
</p>
</div>
</div>
<?php }
?>
<div class="col-12 d-flex flex-sm-row flex-column justify-content-end">
<button type="submit" name="submit" class="btn btn-primary mr-sm-1 mb-1 mb-sm-0">Save
changes</button>
<button type="reset" class="btn btn-outline-warning">Cancel</button>
</div>
</div>
</form>

Related

How to make PHP register errors go underneath their dedicated input boxes

I'm just wondering if anyone knows how to make the errors shown on this screenshot: https://imgur.com/a/eaTVR9g go underneath their dedicated input boxes like shown on this image: https://imgur.com/a/Sb1AfUj If anyone is kind enough to do it for me I would greatly appreciate it. Thank you!
Here is my code:
<?php
$title = "Register";
include ($_SERVER['DOCUMENT_ROOT'] . '/private/header.php');
if ($AUTH) {
header ('Location: /');
die();
}
if (isset($_POST['go'])) {
$username = $_POST['username'];
$email = strtolower($_POST['email']);
$password = $_POST['password'];
$passwordConfirm = $_POST['confirmPassword'];
$protectedPassword = password_hash($password, PASSWORD_ARGON2I);
// Validation Checks
$errors = array();
$Emailstmt = $db->prepare("SELECT * FROM `Users` WHERE `Email` = :email;");
$Emailstmt->bindParam(':email', $email, PDO::PARAM_STR);
$Emailstmt->execute();
if ($Emailstmt->rowCount() > 0) {
$error[] = 'The email you tried to use is already being used on an different account, please use another one.';
}
$Userstmt = $db->prepare("SELECT * FROM `Users` WHERE `Username` = :username;");
$Userstmt->bindParam(':username', $username, PDO::PARAM_STR);
$Userstmt->execute();
$checkIP = $db->prepare("SELECT count(*) FROM `Users` WHERE `LastIP` = :regIP");
$checkIP->bindParam(":regIP", $UserIP, PDO::PARAM_STR);
$checkIP->execute();
$checkIpAdress = $checkIP->fetchColumn();
if (empty($checkIpAdress)) {
$checkIpAdress = 0;
}
if ($checkIpAdress) {
if ($checkIpAdress > 3) {
array_push($errors, 'It looks like you have registered too many accounts under this IP address.');
}
}
if (strlen($username) < 3) {
array_push($errors, 'Your username must be at least 3 characters in total.');
}
if (strlen($password) < 5) {
array_push($errors, 'Your password must be at least 5 characters in total.');
}
if ($Userstmt->rowCount() > 0) {
array_push($errors, 'The username you tried to use is already being used, Maybe try to pick another one.');
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//echo("$email is a valid email address");
} else {
array_push($errors, 'The email you specified(' . htmlspecialchars($email, ENT_QUOTES, "UTF-8") . ') is invaild.');
}
if (!preg_match("/^[a-zA-Z0-9][\w\.]+[a-zA-Z0-9]$/", $username)) {
array_push($errors, 'The username you specified(' . htmlspecialchars($username, ENT_QUOTES, "UTF-8") . ') contains special symbols or is invaild.');
}
if (strtolower($username) == strtolower($password)) {
array_push($errors, 'Your password can not be the same as your username.');
}
if ($password !== $passwordConfirm) {
array_push($errors, 'It looks like your passwords do not match.');
}
// Begin form submission
if (empty($errors)) {
$insert = $db->prepare("INSERT INTO `Users` (`Username`,`Email`,`Password`,`LastIP`,`TimeRegister`,`AvatarURL`) VALUES (:Username,:Email,:Password,:LastIP,:TimeRegister,:AvatarURL)");
$insert->bindParam(":Username", $username, PDO::PARAM_STR);
$insert->bindParam(":Email", $email, PDO::PARAM_STR);
$insert->bindParam(":Password", $protectedPassword, PDO::PARAM_STR);
$insert->bindParam(":LastIP", $UserIP, PDO::PARAM_STR);
$insert->bindParam(":TimeRegister", $now, PDO::PARAM_INT);
$insert->bindValue(":AvatarURL", '8ca17bec-0320-4293-90e5-dfc5b8690156', PDO::PARAM_STR);
$insert->execute();
?>
<div class="space">
<section class="hero is-success">
<div class="hero-body modal-button" data-target="modal" aria-haspopup="true"
style="padding: 1rem 1rem !important;">
<center>You have successfully registered! Please wait while we redirect you.</center>
</div>
</section><br>
</div>
<meta http-equiv='refresh' content='5;url=/auth/login' />
<?php
} else {
}
}
if ($SiteSettings->Registration == 0) {
echo '<section class="section">
<div class="container">
<div class="columns is-centered">
<div class="column is-7">
<div class="box">
<p>We\'re sorry, but account creation is currently disabled right now. Please try again later.</p>
</div>
</div>
</div>
</section>
';
include($_SERVER['DOCUMENT_ROOT'] . "/private/footer.php");
die;
}
?>
<section class="section">
<div class="container">
<div class="columns is-centered">
<div class="column is-7">
<div class="box">
<div class="title is-size-4">Register</div>
<form action="#" method="POST">
<input type="hidden" name="token" value="<?php echo $_SESSION["csrf_token"]; ?>" />
<div class="field">
<label class="label">Username</label>
<div class="control has-icons-left">
<input class="input" name="username" type="text" id="username" maxlength="15"
autocomplete="off" placeholder="Enter a username">
<span class="icon is-small is-left"><i class="fas fa-user"></i></span>
<p id="username_message"></p>
</div>
</div>
<div class="field">
<label class="label">E-Mail address</label>
<div class="control has-icons-left">
<input class="input" name="email" type="email" id="email" maxlength="128"
autocomplete="off" placeholder="Enter your e-mail address.">
<span class="icon is-small is-left"><i class="fas fa-envelope"></i></span>
<p id="email_message"></p>
</div>
</div>
<div class="field">
<label class="label">Password</label>
<div class="control has-icons-left">
<input class="input" name="password" type="password" id="password" maxlength="45"
autocomplete="off" placeholder="Enter your password.">
<span class="icon is-small is-left"><i class="fas fa-lock"></i></span>
<p id="password_message"></p>
</div>
</div>
<div class="field">
<label class="label">Confirm Password</label>
<div class="control has-icons-left">
<input class="input" name="confirmPassword" type="password" id="confirmPassword"
maxlength="45" autocomplete="off" placeholder="Confirm your password">
<span class="icon is-small is-left"><i class="fas fa-lock"></i></span>
<p id="confirmPassword_message"></p>
</div>
</div>
<div class="push-5"></div>
<button class="button is-success is-fullwidth" type="submit" name="go"><b>Register</b></button>
</form>
<?php
if (!empty($errors)) {
?>
<?php
foreach ($errors as $error) {
echo '<p class="help has-text-danger">' . $error . '</p>';
}
} ?>
</div>
<p class="has-text-centered">Already a member? Login</p>
</div>
</div>
</div>
</section>
<?php include ($_SERVER['DOCUMENT_ROOT'] . '/private/footer.php'); ?>
You can organize the array keys to reflect the fields they relate to, IE:
if (strlen($username) < 3) {
$errors['username'][] = 'Your username must be at least 3 characters in total.';
}
and then on the display side you can use said keys to identify what errors belong to what field, IE:
<div class="field">
<label class="label">Username</label>
<div class="control has-icons-left">
<input class="input" name="username" type="text" id="username" maxlength="15" autocomplete="off" placeholder="Enter a username">
<span class="icon is-small is-left"><i class="fas fa-user"></i></span>
<p id="username_message">
<?php if (isset($errors['username'])): ?>
<?php foreach($errors['username'] as $error): ?>
<?= $error ?> <br/>
<?php endforeach; ?>
<?php endif; ?>
</p>
</div>

array to string error in multiple ulpoad files

I Have A form that's have two inputs file one regular and the second is multiple and in one if statment i get them both but in the part
if (!empty($_FILES['logo']['name']) && !empty($_FILES['materials']['name']))
the
$_FILES['materials']
is the multiple
i have tried to
json_encode()
the
$_FILES['materials']
but isn't work, its not pass the first if to the
is_uploaded_file()
/php/
define('IMG_MAX_SIZE', 1024 * 1024 * 5);
if (isset($_POST['submit'])) {
$ex = ['jpg', 'png', 'jpeg', 'gif', 'bmp'];
if (!empty($_FILES['logo']['name']) && !empty($_FILES['materials']['name'])
) {
$matToStr = json_encode($_FILES['materials']);
if (is_uploaded_file($_FILES['logo']['tmp_name']) &&
is_uploaded_file($matToStr)) {
echo "in";
if ($_FILES['logo']['error'] == 0 && $_FILES['logo']['size'] <=
IMG_MAX_SIZE && $_FILES['materials']['error'] == 0 &&
$_FILES['materials']['size'] <= IMG_MAX_SIZE) {
echo "in2";
$logoInfo = pathinfo($_FILES['logo']['name']);
$materialsInfo = pathinfo($_FILES['materials']['name']);
if (in_array(strtolower($logoInfo['extension']), $ex) && in_array(strtolower($materialsInfo['extension']), $ex)) {
$logo = date('Y.m.d.H.i.s') . '-' . $_FILES['logo']['name'];
$materials = date('Y.m.d.H.i.s') . '-' . $_FILES['materials']['name'];
$_SESSION['logo'] = $logo;
$_SESSION['materials'] = $materials;
move_uploaded_file($_FILES['logo']['tmp_name'], 'uploads/' . $logo);
move_uploaded_file($_FILES['materials']['tmp_name'], 'uploads/' . $materials);
$pdo = DB();
$stmt = $pdo->prepare("INSERT INTO client_form_7 (client_id, logo, materials, websites) VALUES (:client_id, :logo, :materials, :websites)");
$stmt->bindParam("client_id", $user_id, PDO::PARAM_INT);
$stmt->bindParam("logo", $logo, PDO::PARAM_STR);
$stmt->bindParam("materials", $materials, PDO::PARAM_STR);
$stmt->bindParam("websites", $websites, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() > 0) {
header('location: client-form-7.php?sm=תמונת הפרופיל עודכנה');
exit;
}
}
}
}
}
}
/html/
<form action="" method="post" class="col s12" enctype="multipart/form-data">
<h4>7. קבצים וחומרים</h4>
<div class="row">
<div class="file-field input-field col s6">
<p>לוגו</p>
<div class="btn">
<span>בחר קובץ</span>
<input type="file" name="logo" id="logo">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
</div>
<div class="row">
<div class="file-field input-field col s6">
<p>צילומים וחומרים שעלולים להיות רלוונטי</p>
<div class="btn">
<span>בחר קובץ</span>
<input type="file" name="materials[]" id="materials" multiple>
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input type="text" name="websites" id="websites" value="<?=old('websites')?>">
<label for="websites">אתרי אינטרנט שניתן למשוך משם חומרים</label>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="submit" class="btn left" value="העלה קבצים" name="submit">
</div>
</div>
</form>
i expected tha'ts upload the one regular file input
and the scond upload like array because i want to fetch it later

Problem with showing image from the database

I need a help regarding my source code on uploading and displaying the profile picture of my users on their profile.
The upload went smooth, but the display is not. The display of the user's picture is only shown in picture icon and not the real picture. Like this:
the file where the picture is stored is here
and here is my source code
edit-profile.php
<div class="author">
<a href="#">
<img class="avatar border-gray" src="../uploads/candidate/<?php echo $row['photo']; ?>" alt="..."/>
<h4 class="title"><?php echo $_SESSION['name']; ?><br /> </h4>
</a>
</div>
EDIT:
I'll provide the full source code for both userindex.php and edit-profile.php here so maybe any of you can point me where I do wrong.
userindex.php
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="header">
<h4 class="title">Edit Profile</h4>
</div>
<div class="content">
<form action="update-profile.php" method="post" enctype="multipart/form-data">
<?php
//Sql to get logged in user details.
$sql = "SELECT * FROM users WHERE id_user='$_SESSION[id_user]'";
$result = $conn->query($sql);
//If user exists then show his details.
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="user_name" type="text" id="user_name"> Full Name</label>
<input name="user_name" class="form-control" type="text" maxlength="100" value="<?php echo $row['user_name'] ?>" required=""/>
</div>
</div>
</div>
<!-- section 1-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="ic_no" type="text" id="ic_no" maxlength="12">NRIC</label>
<input name="ic_no"type="text" class="form-control" value="<?php echo $row['ic_no'] ?>" readonly>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="nationality" type="text" id="nationality">Nationality</label>
<input name="nationality" class="form-control" type="text" id="nationality" value="<?php echo $row['nationality'] ?>"/>
</div>
</div>
</div>
<!--first section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="gender" type="text" id="gender">Gender</label>
<input name="gender" class="form-control" type="text" id="gender" value="<?php echo $row['gender'] ?>"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="race" type="text" id="race">Race</label>
<input type="text" class="form-control" name="race" id="race" value="<?php echo $row['race'] ?>"/>
</div>
</div>
</div>
<!-- second section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="contactno" type="text" id="contact_no">Contact No</label>
<input name="contactno" class="form-control" type="text" id="contact_no" value="<?php echo $row['contactno'] ?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="email" type="text" id="email">Email</label>
<input type="text" class="form-control" type="text" id="email" value="<?php echo $row['email'] ?>" readonly>
</div>
</div>
</div>
<!--other add -->
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="address" type="text" id="address">Current Address</label>
<textarea id="address" name="address" class="form-control" rows="5" placeholder="Address"><?php echo $row['address']; ?></textarea>
</div>
</div>
</div>
<!-- third section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="highest_qualification" type="text" id="highest_qualification">Highest Qualification</label>
<input name="highest_qualification" class="form-control" type="text" maxlength="100" value="<?php echo $row['highest_qualification'] ?>"/>
</div>
</div>
</div>
<!--another section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="university" type="text" id="university">University</label>
<input name="university" class="form-control" type="text" maxlength="100" value="<?php echo $row['university'] ?>"/>
</div>
</div>
</div>
<!--another section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="major" type="text" id="major">Major</label>
<input name="major" class="form-control" type="text" maxlength="100" value="<?php echo $row['major'] ?>"/>
</div>
</div>
</div>
<!-- another section-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="current_position" type="text" id="current_position">Current Position</label>
<input type="text" class="form-control" name="current_position" value="<?php echo $row['current_position'] ?>"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="position_appled" type="text" id="position_applied">Position Applied</label>
<input type="text" class="form-control" name="position_applied" value="<?php echo $row['position_applied'] ?>">
</div>
</div>
</div>
<!--another section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="current_monthly_salary" type="text" id="current_monthly_salary">Current Monthly Salary</label>
<input type="text" class="form-control" name="current_position" value="<?php echo $row['current_monthly_salary'] ?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="expected_monthly_salary" type="text" id="expected_monthly_salary">Expected Monthly Salary</label>
<input type="text" class="form-control" name="position_applied" value="<?php echo $row['expected_monthly_salary'] ?>">
</div>
</div>
</div>
<!--another section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="prefered_working_location" type="text" id="prefered_working_location">Prefered Working Location</label>
<input name="prefered_working_location" class="form-control" type="text" maxlength="100" value="<?php echo $row['prefered_working_location'] ?>" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="avaibility" type="text" id="avaibility">Avaibility</label>
<select name = "avaibility" class="form-control " type="text" id="avaibility" value="<?php echo $row['avaibility'] ?>">
<option value="">-- select one --</option>
<option value="Immediately">Immediately</option>
<option value="One Month">One Month</option>
<option value="Two Month">Two Month</option>
<option value="Three Month">Three Month</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="language" type="text" id="language">Language Proficiency</label><br />
&nbsp&nbsp&nbsp<p>Proficiency level 0-poor; 10-excellent</p>
<table border="2" bordercolor="gray" align="center">
<tr>
<td>
<label for="malay" type="text" id="malay" placeholder="Malay" style="color:black; width:200px"><b>Malay</b></label><br />
</td>
<td>
<input name="malay" type="text" class="form-control" maxlength="100" style="width: 200px" value="<?php echo $row['malay'] ?>"/>
</td>
</tr>
<tr>
<td>
<label for="english" type="text" id="english" placeholder="English" style="color:black; width:200px"><b>English</b></label><br />
</td>
<td>
<input name="english" type="text" class="form-control" maxlength="100" style="width: 200px" value="<?php echo $row['english'] ?>"/>
</td>
</tr>
<tr>
<td>
<label for="mandarin" type="text" id="mandarin" placeholder="Mandarin" style="color:black; width:200px"><b>Mandarin</b></label><br />
</td>
<td>
<input name="mandarin" type="text" class="form-control" maxlength="100" style="width: 200px" value="<?php echo $row['mandarin'] ?>"/>
</td>
</tr>
<tr>
<td>
<label for="other" type="text" id="other" placeholder="Other" style="color:black; width:200px"><b>Others</b></label><br />
</td>
<td>
<input name="other" type="text" class="form-control" maxlength="100" style="width: 200px" value="<?php echo $row['other'] ?>"/>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="aboutme" type="text" id="aboutme"><b>About Me</b></label><br />
<p>Summarize your employement history (Not more than 100 words)</p>
<textarea class="form-control" rows="6" id="aboutme" name="aboutme" maxlength="400" style="width: 560px"value="<?php echo $row['aboutme'] ?>"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label style="color:black;">Latest passport photo</label>
<input class="btn btn-danger" type="file" name="image" id="profile-img" /><br>
<img src="../uploads/candidate/<?php echo $row['photo']; ?>" id="profile-img-tag" width="200px" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label style="color:black;">File format PDF and doc only!</label>
<input type="file" name="resume" class="btn btn-danger" />
</div>
</div>
</div>
<button type="submit" class="btn btn-info btn-fill pull-right">Update Profile</button>
<div class="clearfix"></div>
<?php
}
}
?>
</form>
<?php if(isset($_SESSION['uploadError'])) { ?>
<div class="row">
<div class="col-md-12 text-center">
<?php echo $_SESSION['uploadError']; ?>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<!--second part of picture and resume -->
<div class="col-md-4">
<div class="card card-user">
<div class="image">
<img src="https://ununsplash.imgix.net/photo-1431578500526-4d9613015464?fit=crop&fm=jpg&h=300&q=75&w=400" alt="..."/>
</div>
<div class="content">
<div class="author">
<a href="#">
<img class="avatar border-gray" src="../uploads/candidate/<?php echo $row['photo']; ?>" alt="..."/>
<h4 class="title"><?php echo $_SESSION['name']; ?><br /> </h4>
</a>
</div>
</div>
<hr>
<div class="text-center">
<button href="#" class="btn btn-simple"><i class="fa fa-facebook-square"></i></button>
<button href="#" class="btn btn-simple"><i class="fa fa-twitter"></i></button>
<button href="#" class="btn btn-simple"><i class="fa fa-google-plus-square"></i></button>
</div>
</div>
</div>
</div>
</div>
and this is update-profile.php
<?php
//To Handle Session Variables on This Page
session_start();
if(empty($_SESSION['id_user'])) {
header("Location: ../index.php");
exit();
}
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("../db.php");
//if user Actually clicked update profile button
if(isset($_POST)) {
//Escape Special Characters
if(isset($_POST)) {
$user_name = mysqli_real_escape_string($conn, $_POST['user_name']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$nationality = mysqli_real_escape_string($conn, $_POST['nationality']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$race = mysqli_real_escape_string($conn, $_POST['race']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$contactno = mysqli_real_escape_string($conn, $_POST['contactno']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$highest_qualification = mysqli_real_escape_string($conn, $_POST['highest_qualification']);
$university = mysqli_real_escape_string($conn, $_POST['university']);
$major = mysqli_real_escape_string($conn, $_POST['major']);
$current_position = mysqli_real_escape_string($conn, $_POST['current_position']);
$position_applied = mysqli_real_escape_string($conn, $_POST['position_applied']);
$current_monthly_salary = mysqli_real_escape_string($conn, $_POST['current_monthly_salary']);
$expected_monthly_salary = mysqli_real_escape_string($conn, $_POST['expected_monthly_salary']);
$prefered_working_location = mysqli_real_escape_string($conn, $_POST['prefered_working_location']);
$avaibility = mysqli_real_escape_string($conn, $_POST['avaibility']);
$malay = mysqli_real_escape_string($conn, $_POST['malay']);
$english = mysqli_real_escape_string($conn, $_POST['english']);
$mandarin = mysqli_real_escape_string($conn, $_POST['mandarin']);
$other = mysqli_real_escape_string($conn, $_POST['other']);
$aboutme = mysqli_real_escape_string($conn, $_POST['aboutme']);
$uploadOk = true;
if(isset($_FILES)) {
$folder_dir = "../uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['resume']['tmp_name'])) {
if($resumeFileType == "pdf") {
if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
header("Location: edit-profile.php");
exit();
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
header("Location: edit-profile.php");
exit();
}
}
} else {
$uploadOk = false;
}
//Update User Details Query
$sql= "UPDATE users set user_name='$user_name', ic_no='$ic_no', gender='$gender', nationality='$nationality', race='$race', email='$email', contactno='$contactno', highest_qualification='$$highest_qualification',
university='$university', major='$major', current_position='$current_position', position_applied='$position_applied', current_monthly_salary='$current_monthly_salary',
expected_monthly_salary='$expected_monthly_salary', prefered_working_location='$prefered_working_location', avaibility='$avaibility', malay='$malay', english='$english',
mandarin='$mandarin', other='$other', photo='$file', resume='$file', aboutme='$aboutme'";
if($uploadOk == true) {
$sql .= ", resume='$file'";
}
$sql .= " WHERE id_user='$_SESSION[id_user]'";
if($conn->query($sql) === TRUE) {
$_SESSION['user_name'] = $user_name;
//If data Updated successfully then redirect to dashboard
header("Location: index.php");
exit();
} else {
echo "Error ". $sql . "<br>" . $conn->error;
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to dashboard page if they didn't click update button
header("Location: edit-profile.php");
exit();
}};
Check your update-profile.php
There's confusion happened there because you put the same 'file name' for both your file type for image and resume. You should do it like this instead
<?php
//To Handle Session Variables on This Page
session_start();
if(empty($_SESSION['id_user'])) {
header("Location: ../index.php");
exit();
}
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("../db.php");
//if user Actually clicked update profile button
if(isset($_POST)) {
//Escape Special Characters
if(isset($_POST)) {
$user_name = mysqli_real_escape_string($conn, $_POST['user_name']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$nationality = mysqli_real_escape_string($conn, $_POST['nationality']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$race = mysqli_real_escape_string($conn, $_POST['race']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$contactno = mysqli_real_escape_string($conn, $_POST['contactno']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$highest_qualification = mysqli_real_escape_string($conn, $_POST['highest_qualification']);
$university = mysqli_real_escape_string($conn, $_POST['university']);
$major = mysqli_real_escape_string($conn, $_POST['major']);
$current_position = mysqli_real_escape_string($conn, $_POST['current_position']);
$position_applied = mysqli_real_escape_string($conn, $_POST['position_applied']);
$current_monthly_salary = mysqli_real_escape_string($conn, $_POST['current_monthly_salary']);
$expected_monthly_salary = mysqli_real_escape_string($conn, $_POST['expected_monthly_salary']);
$prefered_working_location = mysqli_real_escape_string($conn, $_POST['prefered_working_location']);
$avaibility = mysqli_real_escape_string($conn, $_POST['avaibility']);
$malay = mysqli_real_escape_string($conn, $_POST['malay']);
$english = mysqli_real_escape_string($conn, $_POST['english']);
$mandarin = mysqli_real_escape_string($conn, $_POST['mandarin']);
$other = mysqli_real_escape_string($conn, $_POST['other']);
$aboutme = mysqli_real_escape_string($conn, $_POST['aboutme']);
$uploadOk = true;
if(isset($_FILES)) {
$folder_dir = "../uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
//notice that I changed your file name from $file to $file1
$file1 = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file1;
if(file_exists($_FILES['resume']['tmp_name'])) {
if($resumeFileType == "pdf") {
if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
header("Location: edit-profile.php");
exit();
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
header("Location: edit-profile.php");
exit();
}
}
} else {
$uploadOk = false;
}
//image update edit
if(is_uploaded_file ( $_FILES['image']['tmp_name'] )) {
$folder_dir = "../uploads/logo/";
$base = basename($_FILES['image']['name']);
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $imageFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['image']['tmp_name'])) {
if($imageFileType == "jpg" || $imageFileType == "png") {
if($_FILES['image']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
header("Location: edit-profile.php");
exit();
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only jpg & png Allowed";
header("Location: edit-profile.php");
exit();
}
}
} else {
$uploadOk = false;
}
//Update User Details Query
$sql= "UPDATE users set user_name='$user_name', ic_no='$ic_no', gender='$gender', nationality='$nationality', race='$race', email='$email', contactno='$contactno', highest_qualification='$$highest_qualification',
university='$university', major='$major', current_position='$current_position', position_applied='$position_applied', current_monthly_salary='$current_monthly_salary',
expected_monthly_salary='$expected_monthly_salary', prefered_working_location='$prefered_working_location', avaibility='$avaibility', malay='$malay', english='$english',
mandarin='$mandarin', other='$other', logo='$file', resume='$file1', aboutme='$aboutme'";
if($uploadOk == true) {
$sql .= ", resume='$file'";
}
$sql .= " WHERE id_user='$_SESSION[id_user]'";
if($conn->query($sql) === TRUE) {
$_SESSION['user_name'] = $user_name;
//If data Updated successfully then redirect to dashboard
header("Location: edit-profile.php");
exit();
} else {
echo "Error ". $sql . "<br>" . $conn->error;
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to dashboard page if they didn't click update button
header("Location: edit-profile.php");
exit();
}};
I have tried your previous code, that cause the image to be stored as pdf and that's why when you call for the image to be displayed, it's appears as broken image icon instead. I hope this can help you well and good luck!
Try this code
<img src="uploads/candidate/.'<?php echo row['photo']; ?>'"/>
You need to make sure the $row value actually got value.
try this and see if you got any result:
die(var_dump("../uploads/candidate/".$row['photo'] ));
You will get the path the code is refering to, if that doesn't give a result check your query again ( check if the row got value )
You can do this introducing an external php file e.g get.php, then request the photo from this get.php.
See sample of both files below.
display.php file
<?php
$id = row['id'];
<img class="avatar" src=get.php?id=$id alt="profile photo" />
?>
get.php file
<?php
// make connections with database here
$id = $_REQUEST['id'];
$image = ("SELECT * FROM table WHERE id = '$id'");
$image = $image->fetch_assoc();
$image = $image['photo'];
echo $image;
?>
You have problem in your $_SESSION array userindex.php file. You have missed the quites ' for session key
$sql = "SELECT * FROM users WHERE id_user='$_SESSION[id_user]'";
So assign it to a variable first and then put that variable inside sql query
$id_user = $_SESSION['id_user'];// single quotes for session key
$sql = "SELECT * FROM users WHERE id_user='$id_user'";
Note:
Your code is open to sql injections. Try use PDO or prepared statements

Issue when trying to update clients info

I'm having an issue where when I go to upload or update a client, it will automatically take the clients profile off if you do not add an image to upload. But If I just want to update their website or motto, and click update, I don't want to have to try and search their image down again and upload it just to update a few items. Any Ideas on why it's doing this? Thank You In Advance.
Heres my code:
<?php
//Gets The Users info when editing it.
$stmt = $DB_con->prepare('SELECT * FROM sponsors WHERE id='.$id);
$stmt->execute();
if($stmt->rowCount() > 0)
{
$row=$stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
}
?>
<div class="col-xs-12 col-sm-6 col-md-8">
<form method="post" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label for="sponsor_name" class="col-sm-3 control-label">Sponsor Name:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_name" id="sponsor_name" value="<?php echo $name;?>">
</div>
</div>
<div class="form-group">
<label for="sponsor_phone" class="col-sm-3 control-label">Sponsor Phone Number:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_phone" id="sponsor_phone" value="<?php echo $phone;?>">
</div>
</div>
<div class="form-group">
<label for="sponsor_moto" class="col-sm-3 control-label">Sponsors Motto:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_motto" id="sponsor_motto" value="<?php echo $motto;?>">
</div>
</div>
<div class="form-group">
<label for="sponsors_website" class="col-sm-3 control-label">Sponsors Website:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_website" id="sponsor_website" value="<?php echo $website;?>">
</div>
</div>
<div class="form-group">
<label for="sponsor_on" class="col-sm-3 control-label">Sponsor on or off?:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sponsor_on" id="sponsor_on" value="<?php echo $live;?>">
</div>
</div>
<div class="form-group">
<label for="image" class="col-sm-3 control-label"> Profile Picture </label>
<div class="col-sm-9">
<p><img id="image" src="../images/sponsors/<?php echo $row['logo'];?>" height="150" width="150" /></p>
<div class="col-sm-9">
<input class="input-group" type="file" name="user_image" accept="image/*" />
</div>
<br>
<br>
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" name="btn_save_updates" class="btn btn-info waves-effect waves-light">Update Sponsor</button>
Delete Sponsor</button>
</div>
</div>
</div>
</form>
Heres my PHP code that will update the Database.
<?php
if(isset($_GET['edit_id']) && !empty($_GET['edit_id']))
{
$id = $_GET['edit_id'];
$stmt_edit = $DB_con->prepare('SELECT * FROM sponsors WHERE id =:uid');
$stmt_edit->execute(array(':uid'=>$id));
$edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
extract($edit_row);
}
else
{
header("Location: ../../login.php");
}
if(isset($_POST['btn_save_updates']))
{
$username = $_POST['user_name'];
$description = $_POST['description'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if($imgFile)
{
$upload_dir = '../images/sponsors/';
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userprofile = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 5000000)
{
unlink($upload_dir.$edit_row['logo']);
move_uploaded_file($tmp_dir,$upload_dir.$userprofile);
}
else
{
$errMSG = "Sorry, Your File Is Too Large To Upload. It Should Be Less Than 5MB.";
}
}
else
{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF Extension Files Are Allowed.";
}
}
else
{
$userprofile = $edit_row['userprofile'];
}
if(!isset($errMSG))
{
$sponsorname = $_POST['sponsor_name'];
$motto = $_POST['sponsor_motto'];
$phone = $_POST['sponsor_phone'];
$website = $_POST['sponsor_website'];
$son = $_POST['sponsor_on'];
$stmt = $DB_con->prepare('UPDATE sponsors SET name=:sname, motto=:smotto, phone=:sphone,website=:swebsite,live=:son, logo=:upic WHERE id=:uid');
$stmt->bindParam(':sname',$sponsorname);
$stmt->bindParam(':smotto',$motto);
$stmt->bindParam(':sphone',$phone);
$stmt->bindParam(':swebsite',$website);
$stmt->bindParam(':son',$son);
$stmt->bindParam(':upic',$userprofile);
$stmt->bindParam(':uid',$id);
if($stmt->execute()){
?>
<script>
alert('Successfully Updated...');
window.location.href='managesponsors.php?action=sponsorupdated';
</script>
<?php
}
else{
$errMSG = "Sorry User Could Not Be Updated!";
}
}
}
?>

My PHP signup form not working

I have created a signup form for my php website using Bootstrap but nothing happens when I click on register. Signup form is made in Bootstrap and it is not working.
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<?php
require_once("company-db.php");
if (!isset($_POST['submit'])) {
?>
<form role="form" action="<?=$_SERVER['PHP_SELF']?>" method="post">
<h2>Please Sign Up <small>It's free and always will be.</small></h2>
<hr class="colorgraph">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg" placeholder="Username" tabindex="1">
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="2">
</div>
</div>
</div>
<div class="form-group">
<input type="text" name="company_name" id="company_name" class="form-control input-lg" placeholder="Company Name" tabindex="3">
</div>
<div class="form-group">
<input type="text" name="description" id="description" class="form-control input-lg" placeholder="Company Description" tabindex="4">
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" tabindex="4">
</div>
<div class="row">
<div class="col-xs-4 col-sm-3 col-md-3">
<span class="button-checkbox">
<button type="button" class="btn" data-color="info" tabindex="7">I Agree</button>
<input type="checkbox" name="t_and_c" id="t_and_c" class="hidden" value="1">
</span>
</div>
<div class="col-xs-8 col-sm-9 col-md-9">
By clicking <strong class="label label-primary">Register</strong>, you agree to the Terms and Conditions set out by this site, including our Cookie Use.
</div>
</div>
<hr class="colorgraph">
<div class="row">
<div class="col-xs-12 col-md-6"><input type="submit" value="submit" class="btn btn-primary btn-block btn-lg" tabindex="7"></div>
<div class="col-xs-12 col-md-6">Sign In</div>
</div>
</form>
<?php
} else {
## connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
## query database
# prepare data for insertion
$username = $_POST['username'];
$password = $_POST['password'];
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$email = $_POST['email'];
# check if username and email exist else insert
$exists = 0;
$result = $mysqli->query("SELECT username from companies WHERE username = '{$username}' LIMIT 1");
if ($result->num_rows == 1) {
$exists = 1;
$result = $mysqli->query("SELECT email from companies WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 2;
} else {
$result = $mysqli->query("SELECT email from companies WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 3;
}
if ($exists == 1) echo "<p>Username already exists!</p>";
else if ($exists == 2) echo "<p>Username and Email already exists!</p>";
else if ($exists == 3) echo "<p>Email already exists!</p>";
else {
# insert data into mysql database
$sql = "INSERT INTO `companies` (`id`, `username`, `password`, `company_name`, `description`, `email`)
VALUES (NULL, '{$username}', '{$password}', '{$company_name}', '{$description}', '{$email}')";
if ($mysqli->query($sql)) {
//echo "New Record has id ".$mysqli->insert_id;
echo "<p>Registred successfully!</p>";
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
}
?>
</div>
</div>
You don't have a name for your submit button, so this won't get posted.
<input type="submit" value="submit" name="submit"
class="btn btn-primary btn-block btn-lg" tabindex="7">
Give the name attribute and make it set.
Note: You must never rely on Submit button's attribute!
The (!isset($_POST['submit'])) conditional statement depends on the execution of your code.

Categories