I'm having a difficult time understanding the $_SESSION function in PHP. I'm building a multipage form and when it was a single form, everything worked as expected. Now I'm trying to figure out $_SESSION so that data from page1 carries to page2 for the submit.
So here is page 1:
<?php require_once("../tim/includes/validation_functions.php");
include("../tim/includes/session.php");
require_once("../tim/includes/variables.php");
include ("/testing/tim/obervation-upload.php");
?>
<?php
session_start(); // Session starts here.
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap.css">
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap-theme.min.css">
<script type="text/javascript" src="/testing/tim/js/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="/testing/tim/js/bootstrap.min.js"></script>
<title>Assessment Application</title>
</head>
<body>
<div>
<h2>3SP Assessment</h2>
<span id="error">
<!---- Initializing Session for errors --->
<?php
if (!empty($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
?>
</span>
<form class="form-horizontal" role="form" name="assessment" action="application_form.php" method="post">
<div class="form-group" style="margin-bottom:10px;">
<label for="company_name" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Company name:</strong></label>
<div class="col-md-2"> <input type="text" id="company_name" name="company_name" class="form-control" required> </div>
<div class="clearfix"></div>
<label for="date" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Date:</strong></label>
<div class="col-md-2"><input type="date" name="date" id="date" class="form-control" required> </div>
<div class="clearfix"></div>
<label for="rsm" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Regional Sales Manager:</strong></label>
<div class="col-md-2"> <input type="text" name="rsm" id="rsm" class="form-control" required></div>
<div class="clearfix"></div>
<label for="agents" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Agents:</strong> </label>
<div class="col-md-2"> <input type="text" name="agents" id="agents" class="form-control" required></div>
<div class="clearfix"></div>
<label for="distributor" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Distributor:</strong> </label>
<div class="col-md-2"><input type="text" name="distributor" class="form-control" required></div>
</div>
<p style="margin-left:5px;"><input class="btn btn-danger" type="reset">
<input style="margin-left:10px;" class="btn btn-success" type="submit" value="Next" /></p>
</form>
<p class="pull-left"><a type="button" class="btn btn-default" href="http://us.pipglobal.com/en/" target="_blank">Cancel</a></p>
</div>
</body>
</html>
page 2:
<?php require_once("../tim/includes/validation_functions.php");
include("../tim/includes/session.php");
require_once("../tim/includes/variables.php");
include ("/testing/tim/obervation-upload.php");
?>
<?php
session_start();
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap.css">
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap-theme.min.css">
<script type="text/javascript" src="/testing/tim/js/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="/testing/tim/js/bootstrap.min.js"></script>
<title>Assessment Application</title>
</head>
<body>
<div>
<h2>3SP Assessment</h2>
<form name="assessment" action="create_new_record.php" method="POST" enctype="multipart/form-data">
<p>Department name: <input type="text" name="department_name" /> </p>
<p>Participant name: <input type="text" name="participant_name" /> </p>
<p>Activity performed: <textarea cols="25" rows="3" name="activity" ></textarea> </p>
<p>Location: <input type="text" name="location" /> </p>
<p>Conditon: <select class="form-control" name="condition" style="width:20%;">
<option value="dry" id="dry">Dry</option>
<option value="heavy_oil" id="heavy_oil">Heavy Oil/Grease</option>
<option value="light_oil" id="light_oil">Light Oil</option>
<option value="sandy" id="sandy">Sandy/Grit</option>
<option value="wet" id="wet">Slightly Wet</option>
</select></p>
<div class="well">
<p>Avg Number of Recordable Injuries:
<input type="number" name="injuries" />
<select name="injury_time_frame">
<option value="last month">Last month</option>
<option value="last 6 months">Last 6 months</option>
<option value="last 12 months">Last 12 months</option>
</select>
</p>
<h4>Based on the number of Recordable Injuries - Estimate the Injury Type by Percentage </h4>
<div class="container-fluid">
<div class="form-group row">
<div class="col-md-3 col-sm-4"><input class="form-control" id="cuts" name="cuts" type="number" min="0" max="100" value="" placeholder="Cuts / Lacerations / Abrasion" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="burns" name="burns" type="number" min="0" max="100" value="" placeholder="Heat or Chemical Burn" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="infection" name="infection" type="number" min="0" max="100" value="" placeholder="Infection" /> </div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="dermatitis" name="dermatitis" type="number" min="0" max="100" value="" placeholder="Dermatitis" /> </div>
<div class="clearfix visible-xs-block"></div> <div class="hidden-xs hidden-sm"><br /><br /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="puncture" name="puncture" type="number" min="0" max="100" value="" placeholder="Puncture" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="sprain" name="sprain" type="number" min="0" max="100" value="" placeholder="Carpal Tunnel / Sprain" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="impact" name="impact" type="number" min="0" max="100" value="" placeholder="Impact / Contusion / Inflammation" /> </div>
</div>
</div>
<p id="rec_injuries"></p>
<script>
function percentageTest() {
// Get the value of the input fields
a = document.getElementById("cuts").value;
b = document.getElementById("burns").value;
c = document.getElementById("infection").value;
d = document.getElementById("dermatitis").value;
e = document.getElementById("puncture").value;
f = document.getElementById("sprain").value;
g = document.getElementById("impact").value;
var x = (a + b + c + d + e + f + g);
// grouping together and doing the math
if (x = !100) {
text = "The total percentage must equal 100%";
} else {
text = "Congrats the total = 100%";
}
document.getElementById("rec_injuries").innerHTML = text;
}
</script>
</div>
<div class="well">
<p>Avg Number of Non-recordable Injuries: <input type="number" name="non_rec_injuries" />
<select name="non_rec_injury_timeframe">
<option value="last month">Last month</option>
<option value="last 6 months">Last 6 months</option>
<option value="last 12 months">Last 12 months</option>
</select>
</p>
<h4>Based on the number of Non-recordable Injuries - Estimate the Injury Type by Percentage </h4>
<div class="container-fluid">
<div class="form-group row">
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_cuts" type="number" min="0" max="100" value="" placeholder="Cuts / Lacerations / Abrasion" /> </div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_burns" type="number" min="0" max="100" value="" placeholder="Heat or Chemical Burn" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_infection" type="number" min="0" max="100" value="" placeholder="Infection" /> </div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_dermatitis" type="number" min="0" max="100" value="" placeholder="Dermatitis" /> </div>
<div class="clearfix visible-xs-block"></div> <div class="hidden-xs hidden-sm"><br /><br /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_puncture" type="number" min="0" max="100" value="" placeholder="Puncture" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_sprain" type="number" min="0" max="100" value="" placeholder="Carpal Tunnel / Sprain" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_impact" type="number" min="0" max="100" value="" placeholder="Impact / Contusion / Inflammation" />
</div>
</div>
</div>
</div>
<p>Estimated Cost of Productivity (Downtime)/minute: $ <input type="number" name="cost_of_productivity" /> </p>
<p>Percent of leakage related to uncontrolled dispensing: <input type="number" min="0" max="100" name="leakage" /> % </p>
<p>Which competitor is the participant using? <input type="text" name="competitor" /></p>
<p>Usage Rate per 12 months (pairs): <input type="number" min="0" name="usage_rate" /></p>
<p>Estimated cost per pair: $ <input type="number" min="0" name="cost_per_pair" /></p>
<br />
<div class="container" style="margin-left:0px; padding-left:0px;">
<div class="form-group row" style="margin-left:0px;">
<div class="col-md-3 col-sm-6">
<label for="safetyHazard1_notes"><strong>Safety observation 1:</strong></label> <input type="file" name="safetyHazard1" id="safetyHazard1" value=""><br /> <br />
<textarea cols="25" rows="3" id="safetyHazard1_notes" name="safetyHazard1_notes" placeholder="Enter notes for this observation" ></textarea> </div>
<div class="col-md-3 col-sm-6">
<label for="safetyHazard2_notes"><strong>Safety observation 2:</strong></label> <input type="file" name="safetyHazard2" id="safetyHazard2" value=""><br /><br />
<textarea cols="25" rows="3" id="safetyHazard2_notes" name="safetyHazard2_notes" placeholder="Enter notes for this observation" ></textarea> </div>
<div class="col-md-3 col-sm-6">
<label for="safetyHazard3_notes"><strong>Safety observation 3:</strong></label> <input type="file" name="safetyHazard3" id="safetyHazard3" value=""><br /><br />
<textarea cols="25" rows="3" id="safetyHazard2_notes" name="safetyHazard2_notes" placeholder="Enter notes for this observation" ></textarea> </div>
<div class="col-md-3 col-sm-6">
<label for="other_notes"><strong>Other observations:</strong></label> <input type="file" name="otherObservation" id="otherObservation" value=""><br /><br />
<textarea cols="25" rows="3" id="other_notes" name="other_notes" placeholder="Enter notes for this observation" ></textarea> </div>
</div></div>
<br />
<p style="margin-left:5px;"><input class="btn btn-danger" type="reset">
<input style="margin-left:10px;" class="btn btn-primary" type="button" name="new_location" value="Add Additional Location" />
<input style="margin-left:10px;" class="btn btn-success" type="submit" name="submit" value="Create New Assessment" /></p>
</form>
<p class="pull-left"><a type="button" class="btn btn-default" href="http://us.pipglobal.com/en/" target="_blank">Cancel</a></p>
</div>
</body>
</html>
And finally the processing page:
<?php
require_once("../tim/includes/session.php");
require_once ("../tim/includes/functions.php");
require_once("../tim/includes/validation_functions.php");
?>
<?php
if(isset($_POST["submit"])) {
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/testing/tim/uploads/';
$target_file = $target_dir . basename($_FILES["safetyHazard1"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["safetyHazard1"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["safetyHazard1"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["safetyHazard1"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["safetyHazard1"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
extract($_SESSION['post']);
// Process the form
$department_name = ($_POST['department_name']);
$participant_name = ($_POST['participant_name']);
$activity = ($_POST['activity']);
$location = ($_POST['location']);
$rec_injuries = ($_POST['injuries']);
$rec_injuries_timeframe = ($_POST['injury_time_frame']);
$non_rec_injuries = ($_POST['non_rec_injuries']);
$non_rec_injuries_timeframe = ($_POST['non_rec_injury_timeframe']);
$rec_cuts = ($_POST['cuts']);
$rec_burns = ($_POST['burns']);
$rec_infection = ($_POST['infection']);
$rec_dermatitis = ($_POST['dermatitis']);
$rec_puncture = ($_POST['puncture']);
$rec_sprain = ($_POST['sprain']);
$rec_impact = ($_POST['impact']);
$non_rec_cuts = ($_POST['non_rec_cuts']);
$non_rec_burns = ($_POST['non_rec_burns']);
$non_rec_infection = ($_POST['non_rec_infection']);
$non_rec_dermatitis = ($_POST['non_rec_dermatitis']);
$non_rec_puncture = ($_POST['non_rec_puncture']);
$non_rec_sprain = ($_POST['non_rec_sprain']);
$non_rec_impact = ($_POST['non_rec_impact']);
$cost_of_productivity = ($_POST['cost_of_productivity']);
$leakage = (($_POST['leakage']) / 100);
$usage_rate = ($_POST['usage_rate']);
$cost_per_pair = ($_POST['cost_per_pair']);
$condition = ($_POST['condition']);
$safety_hazard_1 = basename( $_FILES["safetyHazard1"]["name"]);
$safety_hazard_2 = ($_POST['safetyHazard2']);
$safety_hazard_3 = ($_POST['safetyHazard3']);
$other_observation = ($_POST['otherObservation']);
$safetyHazard1_notes = ($_POST['safetyHazard1_notes']);
$safetyHazard2_notes = ($_POST['safetyHazard2_notes']);
$safetyHazard3_notes = ($_POST['safetyHazard3_notes']);
$otherNotes = ($_POST['otherNotes']);
$competitor = ($_POST['competitor']);
$company_name = ($_POST['company_name']);
$date = ($_POST['date']);
$rsm = ($_POST['rsm']);
$agents = ($_POST['agents']);
$distributor = ($_POST['distributor']);
print "distributor: " . $distributor;
exit;
// Perform first database insert
$query1 = "INSERT INTO location_info (";
$query1 .= "`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries`, `non_rec_injuries_timeframe`, `competitor`, `cost_per_pair`, `usage_rate`, `leakage`, `cost_of_productivity`, `non_rec_impact`, `non_rec_sprain`, `non_rec_puncture`, `non_rec_dermatitis`, `non_rec_infection`, `non_rec_burns`, `non_rec_cuts`, `rec_impact`, `rec_sprain`, `rec_puncture`, `rec_dermatitis`, `rec_infection`, `rec_burns`, `rec_cuts`, `condition`, `safety_hazard_1`, `safety_hazard_2`, `safety_hazard_3`, `other_observation`,`safetyHazard1_notes`, `safetyHazard2_notes`, `safetyHazard3_notes`, `otherNotes`";
$query1 .= ") VALUES (";
$query1 .= " '{$department_name}', '{$participant_name}', '{$activity}', '{$location}', '{$rec_injuries}', '{$rec_injuries_timeframe}',
'{$non_rec_injuries}', '{$non_rec_injuries_timeframe}', '{$competitor}', '{$cost_per_pair}', '{$usage_rate}', '{$leakage}', '{$cost_of_productivity}', '{$non_rec_impact}', '{$non_rec_sprain}', '{$non_rec_puncture}', '{$non_rec_dermatitis}', '{$non_rec_infection}', '{$non_rec_burns}', '{$non_rec_cuts}', '{$rec_impact}', '{$rec_sprain}', '{$rec_puncture}', '{$rec_dermatitis}', '{$rec_infection}', '{$rec_burns}', '{$rec_cuts}', '{$condition}', '{$safety_hazard_1}', '{$safety_hazard_2}', '{$safety_hazard_3}', '{$other_observation}','{$safetyHazard1_notes}', '{$safetyHazard2_notes}', '{$safetyHazard3_notes}', '{$otherNotes}'";
$query1 .= ")";
$result1 = mysqli_query($connection, $query1);
if ($result1) {
// Success
$_SESSION["message"] = "Assessment created.";
redirect_to("results.php");
} else {
// Failure
$_SESSION["message"] = "Assessment creation failed.";
redirect_to("errors.php");
}
// Perform second database insert
$query2 = "INSERT INTO general_assessment (";
$query2 .= "`company_name`, `date`, `rsm`, `agents`, `distributor`";
$query2 .= ") VALUES (";
$query2 .= " '{$company_name}', '{$date}', '{$rsm}', '{$agents}', '{$distributor}'";
$query2 .= ")";
$result2 = mysqli_query($connection, $query2);
if ($result2) {
// Success
$_SESSION["message"] = "Assessment created.";
redirect_to("results.php");
} else {
// Failure
$_SESSION["message"] = "Assessment creation failed.";
redirect_to("errors.php");
}
}
else {
redirect_to($_SERVER["DOCUMENT_ROOT"]."/testing/tim/errors-inserting.php");
}
?>
<?php
if (isset($connection)) { mysqli_close($connection); }
?>
You'll see on the processing page my little test of
print "distributor: " . $distributor;
exit;
this would obviously be removed when working.
Ok I think I've figured this out. I needed to "recall" the session data when I move to page 2.
So on the top of page 2 the code became:
<?php
session_start();
//store the posted values in the session variables
$_SESSION['company_name'] = $_POST['company_name'];
$_SESSION['date'] = $_POST['date'];
$_SESSION['rsm'] = $_POST['rsm'];
$_SESSION['agents'] = $_POST['agents'];
$_SESSION['distributor'] = $_POST['distributor'];
?>
You have to use line session_start(); on every page that you want to use the session - as the first line on top of the file.
You can set variables:
$_SESSION['username'] = "user";
and then retrieve them:
echo $_SESSION['username'];
You can then use session_destroy() to remove the saved session
To use a session variables for PHP at the many files. Try like this :
page1.php
<?php
session_start();
$_SESSION['name'] = 'Example session';
?>
When you use the session variables at the another page :
page2.php
<?php
include 'page1.php';
echo $_SESSION['name']; //Example session
?>
And to destroy session. Use session_destroy(); unset($_SESSION);
Related
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 />
   <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
I'm working on this feature in my project where I want to add three(3) images along side other details into my database row and I want this images to be in separate columns in one row.... So far below is my code. the code is not working yet... The images and texts are not uploading to the database....
Please help me out guys. What am I doing wrong. Thanks.
Below is my code sample:
//THE PHP SECTION//
<?php
session_start();
include 'includes/config.php';
if (isset($_POST['post']) && isset($_POST['itemtype'])) {
$title = mysqli_real_escape_string($link, $_POST['title']);
$itemtype = mysqli_real_escape_string($link, $_POST['itemtype']);
$description = mysqli_real_escape_string($link, $_POST['description']);
$image1 = $_FILES['image1']['name'];
$image1_tmp_name = $_FILES['image1']['tmp_name'];
$image2 = $_FILES['image2']['name'];
$image2_tmp_name = $_FILES['image2']['tmp_name'];
$image3 = $_FILES['image3']['name'];
$image3_tmp_name = $_FILES['image3']['tmp_name'];
$price = mysqli_real_escape_string($link, $_POST['price']);
$category = mysqli_real_escape_string($link, $_POST['category']);
$name = mysqli_real_escape_string($link, $_POST['name']);
//image file directory
$target1 = 'images/user_ads/'.basename($image1);
$target2 = 'images/user_ads/'.basename($image2);
$target3 = 'images/user_ads/'.basename($image3);
if (move_uploaded_file($_FILES['image1_tmp_name'], $target1)) {
}
if (move_uploaded_file($_FILES['image2_tmp_name'], $target2)) {
}
if (move_uploaded_file($_FILES['image3_tmp_name'], $target3)) {
}
//insert into ost database
$insert = "INSERT INTO products(Title,Product_Type,Description,Image1,Image2,Image3,Price,Category,Name,PostedDate)VALUES('$title','$itemtype','$description','$target1','$target2','$target3','$price','$category','$name',NOW())";
$insertKwary = mysqli_query($link, $insert);
if ($insertKwary) {
$msg = "<div class='alert alert-danger alert-success'>Product Submitted</div>";
}else{
$msg = "<div class='alert alert-danger alert-success'>Product Not Submitted...Try again</div>";
}
}
?>
//THE HTML SECTION//
<div class="col-md-8 col-md-offset-2">
<?php if(isset($msg)) { echo $msg; } ?>
<form action="" method="POST" enctype="multipart/form-data" class="postAdForm" id="postAdForm">
<div class="form-group">
<label for="Ad_title">Item Title</label>
<input type="text" name="title" class="form-control title" id="title" required=""/>
</div>
<div class="form-group">
<label for="itemtype">Item Type</label>
<select class="form-control" name="itemtype" id="itemtype">
<option>Sale</option>
<option>Request</option>
</select>
</div>
<div class="form-group">
<label for="description">Item Description</label>
<textarea name="description" class="form-control description" id="description" rows="7" required=""></textarea>
</div>
<div class="form-group">
<label for="price">First Image</label>
<input type="file" name="image1" class="form-control image1" id="image1" required="" />
</div>
<div class="form-group">
<label for="price">Second Image</label>
<input type="file" name="image2" class="form-control image2" id="image2" required="" />
</div>
<div class="form-group">
<label for="price">Third Image</label>
<input type="file" name="image3" class="form-control image3" id="image3" required="" />
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" name="price" class="form-control price" id="price" required="" />
</div>
<div class="form-group">
<label for="category">Item Category</label>
<select class="form-control" name="category" id="category">
<option>Sale</option>
<option>Request</option>
</select>
</div>
<div class="form-group">
<label for="price">Name</label>
<input type="text" name="name" class="form-control name" id="name" required="" readonly="" />
</div>
<div class="form-group">
<input type="submit" name="post" class="btn btn-post post" id="post" value="POST AD" />
</div>
</form>
</div>
I've also attached an image of the error i'm getting..
image of web page showing thee errors i get..error gotten
The error is due to these lines:
if (move_uploaded_file($_FILES['image1_tmp_name'], $target1)) {
}
if (move_uploaded_file($_FILES['image2_tmp_name'], $target2)) {
}
if (move_uploaded_file($_FILES['image3_tmp_name'], $target3)) {
}
You're setting $image1_tmp_name, not $_FILES['image1_tmp_name'].
Try this:
if (move_uploaded_file($image1_tmp_name, $target1)) {
}
if (move_uploaded_file($image2_tmp_name, $target2)) {
}
if (move_uploaded_file($image3_tmp_name, $target3)) {
}
Edit: Using mysqli_error() to print the error helped solve additional issues (Mentioned in comments)
I built a script named add_post.php that submit form data in database.
The script is here:
<?php include ("includes/header.php"); ?>
<div class="content" style="text-align: center;">
<header>
<h1 style="color: rgb(245, 106, 106);">ADMIN AREA</h1><br/>
<p>Movie Post Area</p>
</header>
</div>
</section>
<?php
include("includes/startsession.php");
if(isset($_SESSION['username'])){
?>
<Section>
<?php
if(isset($_POST['submit'])){
$name =mysqli_real_escape_string($con, trim($_POST['name']));
$description = mysqli_real_escape_string($con, trim($_POST['description']));
$year = mysqli_real_escape_string($con, trim($_POST['year']));
$popularity = mysqli_real_escape_string($con, trim($_POST['popularity']));
$download_link = mysqli_real_escape_string($con, trim($_POST['download']));
$tags = mysqli_real_escape_string($con, trim($_POST['tags']));
//upload the name to the temporary folder
$images = mysqli_real_escape_string($con, trim($_FILES['image']['name']));
//select the image from the temporary folder
$images_tmp = $_FILES['image']['tmp_name'];
//move the uploaded image to the `images` folder
move_uploaded_file($images_tmp, "../images/$images");
$output_form = false;
if( empty($name) || empty($description) || empty($year) || empty($popularity) || empty($download_link) || empty($tags) || empty($images)){
echo '<h2>Oops! You seem to forget writing something</h2>';
$output_form = true;
}
if( (!empty($name)) && (!empty($description)) && (!empty($year)) && (!empty($popularity)) && (!empty($download_link)) && (!empty($tags)) && (!empty($images))){
$insert = "INSERT INTO movies (name, description, year, image, popularity, download_link, tags)
VALUES ('$name', '$description', '$year', '$images', '$popularity', '$download_link', '$tags') " or die(mysqli_error);
$run = mysqli_query($con, $insert);
echo "<h2>The Movie has been added.<h2>";
echo 'RESET';
}
} else{
$output_form = true;
$name = '';
$description = '';
$year = '';
$popularity = '';
$download_link = '';
$tags = '';
$images = '';
}
?>
<?php if($output_form = true){ ?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<div class="row uniform">
<div class="6u 12u$(xsmall)" style="float:none">
<label>Movie Name</label>
<input type="text" name="name" value="<?php echo $name; ?>" id="demo-name" value="" placeholder="Enter Movie Name" />
</div>
<br/>
<div class="6u 12u$(xsmall)" style="float:none">
<label>Description</label>
<textarea name="description" id="demo-message" placeholder="Enter Description" rows="6"><?php echo $description; ?></textarea>
</div>
<br/>
<div class="6u 12u$(xsmall)" style="float:none">
<label>Year</label>
<input type="text" name="year" value="<?php echo $year; ?>" id="demo-name" placeholder="Enter Year" />
</div>
<br/>
<div class="6u 12u$(xsmall)" style="float:none">
<label>Image</label>
<input type="file" name="image" value="<?php echo $images; ?>" id="demo-name" class="special" />
</div>
<div class="12u$" style="float:none">
<div class="select-wrapper">
<label>Popularity</label>
<select name="popularity" id="demo-category">
<option <?php if ($popularity == 'Yes'){echo 'selected';} ?> >Yes</option>
<option <?php if ($popularity == 'No'){echo 'selected';} ?> >No</option>
</select>
</div>
</div>
<div class="6u 12u$(xsmall)" style="float:none">
<label>Download Link</label>
<input type="text" name="download" value="<?php echo $download_link; ?>" id="demo-name" value="" placeholder="Enter Download Link" />
</div>
<div class="6u 12u$(xsmall)" style="float:none">
<label>Tags</label>
<input type="text" name="tags" value="<?php echo $tags; ?>" id="demo-name" value="" placeholder="Enter Tags seperated by commas(,)" />
</div>
<!-- Break -->
<div class="12u$" style="float:none">
<ul class="actions">
<li><input type="submit" name="submit" value="ADD MOVIE" class="special" /></li>
</ul>
</div>
</div>
</form>
<?php } ?>
<?php
} else{
header('Location: login.php');
}
?>
when I submit the form the page returns the script of index.php. When i refresh the page then the page shows the content of add_post.php and above all the data content of the form did not add to the database.
I don't know whats causing this problem and how to fix it.
I've been building a site recently for a friend and I've gotten stuck on this one form. A button links to url in which this form is on and then once you fill out all the information and click submit, instead of returning you back to home.php it just removes the form from view and all you see is a blank new.php and it doesn't submit the information.
<?php
function renderForm($user, $rank, $position, $error)
{
?>
<?php
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<center>
<form action="" method="post">
<div class="form-group">
<label for="username">Username*</label>
<input id="username" class="form-control" type="text" name="user" placeholder="Username" value="<?php echo $user; ?>" />
</div>
<div class="form-group">
<label for="rank">Rank</label>
<select class="form-control" name="rank">
<option value="1">Pending Rank</option>
<option value="2">PVT</option>
</select>
</div>
<div class="form-group">
<label for="position">Position</label>
<input id="position" class="form-control" type="text" name="position" placeholder="MOG/GG" value="<?php echo $position; ?>" />
</div>
<div class="form-group">
<label for="Date">Date*</label>
<input id="Date" class="form-control" type="text" name="date" placeholder="<?php echo date('d M y'); ?>" value="<?php echo $date; ?>" />
</div>
<div class="form-group">
<label for="Tag">Tag*</label>
<input id="Tag" class="form-control" type="text" name="tag" placeholder="[]" value="<?php echo $tag; ?>" />
</div>
<div class="form-group">
<label for="adt">ADT</label>
<input id="adt" class="form-control" type="text" name="adt" placeholder="{TEST}" value="<?php echo $adt; ?>" />
</div>
<div class="form-group">
<label for="exp">EXP</label>
<input id="exp" class="form-control" type="text" name="exp" placeholder="420" value="<?php echo $exp; ?>" />
</div>
<div class="form-group">
<label for="reg">Regiment</label>
<input id="reg" class="form-control" type="text" name="reg" placeholder="[P]" value="<?php echo $reg; ?>" />
</div>
<div class="form-group">
<label for="Notes">Notes</label>
<input id="Notes" class="form-control" type="text" name="notes" placeholder="Notes" value="<?php echo $notes; ?>" />
</div>
<button type="submit" name="submit" class="btn btn-default" value="Submit">Submit</button>
</form>
<script>
$('.modal').on('hidden.bs.modal', function(){
$(this).find('form')[0].reset();
});
</script>
<?php
}
include('config/db.php');
if (isset($_POST['submit']))
{
$user = mysql_real_escape_string(htmlspecialchars($_POST['user']));
$rank = mysql_real_escape_string(htmlspecialchars($_POST['rank']));
$position = mysql_real_escape_string(htmlspecialchars($_POST['position']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$tag = mysql_real_escape_string(htmlspecialchars($_POST['tag']));
$adt = mysql_real_escape_string(htmlspecialchars($_POST['adt']));
$exp = mysql_real_escape_string(htmlspecialchars($_POST['exp']));
$reg = mysql_real_escape_string(htmlspecialchars($_POST['reg']));
$notes = mysql_real_escape_string(htmlspecialchars($_POST['notes']));
$datej = mysql_real_escape_string(htmlspecialchars($_POST['date']));
if ($user == '' || $rank == '' || $date == '' || $tag == '')
{
$error = '<center>ERROR: Please fill in all required fields!</center>';
#renderForm($user, $rank, $position, $error);
}
else
{
mysql_query("INSERT per SET user='$user', rank='$rank', position='$position', date='$date', tag='$tag', adt='$adt', exp='$exp', reg='$reg', notes='$notes', datej='$datej'", $db1)
or die(mysql_error());
include('logsadd.php');
write_mysql_log('has added member <font color="black"><b>'. $user .'</b></font>.', $db);
header("Location: home.php");
}
}
else
header("home.php");
{
#renderForm('','','');
}?>
Your else looks like this
else
header("home.php");
{
#renderForm('','','');
it should be
else
{
// header should be inside the else part
header("Location:home.php");
#renderForm('','','');
I would like to ask your help. I wrote a code which checks if all the fields are filled in and if the file is not larger than 1 MB. If everything is correct the file successfuly uploads to MySQL database. But if the file size is larger than 1 MB the code stops working. The error doesnt show up and all the fields become empty. Here`s the code (some of it is in Lithuanian, sorry):
<?php
error_reporting(E_ERROR);
session_start();
if (isset($_SESSION['login'])){
include 'config.php';
$username = $_SESSION['login'];
$result = mysqli_query($db,"SELECT * FROM users WHERE username='$username'");
$rws = mysqli_fetch_array($result);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$autorius = mysqli_real_escape_string($db,$_POST['autorius']);$pavadinimas = mysqli_real_escape_string($db,$_POST['pavadinimas']);$puslapiai = mysqli_real_escape_string($db,$_POST['puslapiai']);$tema = mysqli_real_escape_string($db,$_POST['tema']);$pmintis = mysqli_real_escape_string($db,$_POST['pmintis']);$pveikejai = mysqli_real_escape_string($db,$_POST['pveikejai']);$aveikejai = mysqli_real_escape_string($db,$_POST['aveikejai']);$epizodas = mysqli_real_escape_string($db,$_POST['epizodas']);$nuomone = mysqli_real_escape_string($db,$_POST['nuomone']);$apie = mysqli_real_escape_string($db,$_POST['apie']);$foto = mysqli_real_escape_string($db,$_POST['foto']);$user_id = $rws['id'];
if (!empty($autorius) && !empty($pavadinimas) && !empty($puslapiai) && !empty($tema) && !empty($pmintis) && !empty($pveikejai) && !empty($aveikejai) && !empty($epizodas) && !empty($nuomone) && !empty($apie) && isset($foto) && $_FILES['foto']['size'] > 0 && $_FILES['foto']['size'] < 1000001) {
$fileName = $_FILES['foto']['name'];$tmpName = $_FILES['foto']['tmp_name'];$fileSize = $_FILES['foto']['size'];$fileType = $_FILES['foto']['type'];
$fp = fopen($tmpName, 'r');
$foto = fread($fp, filesize($tmpName));
$foto = addslashes($foto);
fclose($fp);
$query = "INSERT INTO books (id_user, autorius, pavadinimas, puslapiai, tema, pmintis, pveikejai, aveikejai, epizodas, nuomone, apie, foto, name, type, size) ".
"VALUES ('$user_id', '$autorius', '$pavadinimas', '$puslapiai', '$tema', '$pmintis', '$pveikejai', '$aveikejai', '$epizodas', '$nuomone', '$apie', '$foto', '$fileName', '$fileType', '$fileSize')";
$result = mysqli_query($db,$query);
$success = "Knygos aprašymas įkeltas";
echo $_FILES['foto']['size'];
}
else if (empty($autorius) || empty($pavadinimas) || empty($puslapiai) || empty($tema) || empty($pmintis) || empty($pveikejai) || empty($aveikejai) || empty($epizodas) || empty($nuomone) || empty($apie)) {
$error = "Užpildykite visus laukelius!";
}
else if (empty($foto)){
$error = "Pasirinkite viršelio nuotrauką!";
}
else if ($_FILES['foto']['size'] > 1000001){
$error = "Viršelio nuotraukos dydid neturi viršyti 1 MB!";
}
}
?>
<?php include 'bin/includes/header.html'; ?>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Įkelti knygos aprašymą
<small>Ikelkite savo knygos aprašymą</small>
</h1>
<ol class="breadcrumb">
<li>Pagrindinis
</li>
<li class="active">Įkelti knygos aprašymą</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-md-8">
<form name="upload" id="upload" method="post" enctype="multipart/form-data">
<div class="control-group form-group">
<?php
if(isset($success)) {
echo '<label style="color: #44FF00;">';
echo $success;
echo '</label>';
}
else {
echo '<label style="color: #FF3700;">';
echo $error;
echo '</label>';
} ?>
<div class="controls">
<input type="text" class="form-control" name="autorius" maxlength="60" placeholder="Autorius" value="<?php if(!empty($_POST['autorius'])) echo $_POST['autorius'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="pavadinimas" maxlength="255" placeholder="Pavadinimas" value="<?php if(!empty($_POST['pavadinimas'])) echo $_POST['pavadinimas'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="puslapiai" placeholder="Puslapių skaičius" value="<?php if(!empty($_POST['puslapiai'])) echo $_POST['puslapiai'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="pveikejai" maxlength="999" placeholder="Pagrindiniai veikėjai" value="<?php if(!empty($_POST['pveikejai'])) echo $_POST['pveikejai'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="aveikejai" maxlength="999" placeholder="Antraeiliai veikėjai" value="<?php if(!empty($_POST['aveikejai'])) echo $_POST['aveikejai'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Tema" rows="2" class="form-control" name="tema" maxlength="999" style="resize:none"><?php if(!empty($_POST['tema'])) echo $_POST['tema'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Pagrindinė mintis" rows="2" class="form-control" name="pmintis" maxlength="999" style="resize:none"><?php if(!empty($_POST['pmintis'])) echo $_POST['pmintis'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Siužetas" rows="5" class="form-control" name="apie" maxlength="2999" style="resize:none"><?php if(!empty($_POST['apie'])) echo $_POST['apie'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Įsimintiniausias epizodas" rows="3" class="form-control" name="epizodas" maxlength="2999" style="resize:none"><?php if(!empty($_POST['epizodas'])) echo $_POST['epizodas'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Nuomonė apie knygą" rows="3" class="form-control" name="nuomone" maxlength="999" style="resize:none"><?php if(!empty($_POST['nuomone'])) echo $_POST['nuomone'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<label>Įkelti viršelį (max 1MB)</label>
<input name="foto" type="file" id="foto">
<p class="help-block"></p>
</div>
<button type="submit" class="btn btn-primary">Įkelti</button>
</div>
</form>
</div>
</div>
<?php include 'bin/includes/footer.html'; ?>
<?php } else {
header("location: index.php");
}
Thanks for your help!
You should use this to get the file size:
$size = filesize($_FILES['foto']['tmp_name']);
This returns the filesize in byte. One MB are 1048576 bytes. You should check for the function not returning false.
In general: You should use exceptions for this purpose, it is much simplier to check for a condition and then check again. If you just want to use if-else-statements, you should rearrange it (check for errors first and then upload the thing in the else-case).
Why are you not saving the files in filesystem? This is a lot easier...