php script change when submitting a form data - php

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.

Related

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

How to ensure that the form is refilled with the old values only if the insertion failed the last time?

My code is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Insert Item - SomuFinance</title>
<link rel="stylesheet" type="text/css" href="indexStyle.css">
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
</head>
<body>
<div id="addItemContainer">
<h1>Insert Item</h1>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<div class="leftAligned">
<?php
$save_vals = FALSE;
if(!empty($_POST['submit']))
{
$shop = $_POST['shop'];
$category = $_POST['category'];
$item = $_POST['item'];
$qnty = $_POST['qnty'];
$unit = $_POST['unit'];
$price_based_on = $_POST['price_based_on'];
$mrp = $_POST['mrp'];
$sellers_price = $_POST['sellers_price'];
$last_updated_on = $_POST['last_updated_on'];
$save_vals = $_POST['save_vals'];
}
?>
<div class="inp">
<label for="shop">Shop : </label>
<input type="text" id="shop" name="shop" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $shop;} ?>">
</div> <br>
<div class="inp">
<label for="category">Category : </label>
<input type="text" id="category" name="category" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $category;} ?>">
</div> <br>
<div class="inp">
<label for="item">Item : </label>
<input type="text" id="item" name="item" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $item;} ?>">
</div> <br>
<div class="inp">
<label for="qnty">Quantity : </label>
<input type="text" id="qnty" name="qnty" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $qnty;} ?>">
</div> <br>
<div class="inp">
<label for="unit">Unit : </label>
<input type="text" id="unit" name="unit" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $unit;} ?>">
</div> <br>
<div class="inp">
<label for="price_based_on">Price based on : </label>
<select name="price_based_on" id="price_based_on">
<option value="kilos" <?php if((!empty($_POST['submit']))&&($save_vals)){if($price_based_on=='kilos'){echo 'selected';}} ?>>Kilos</option>
<option value="packet" <?php if((!empty($_POST['submit']))&&($save_vals)){if($price_based_on=='packet'){echo 'selected';}} ?>>Packet</option>
<option value="bottle" <?php if((!empty($_POST['submit']))&&($save_vals)){if($price_based_on=='bottle'){echo 'selected';}} ?>>Bottle</option>
<option value="box" <?php if((!empty($_POST['submit']))&&($save_vals)){if($price_based_on=='box'){echo 'selected';}} ?>>Box</option>
<option value="piece" <?php if((!empty($_POST['submit']))&&($save_vals)){if($price_based_on=='piece'){echo 'selected';}} ?>>Piece</option>
</select>
</div> <br>
<div class="inp">
<label for="mrp">MRP (₹) : </label>
<input type="text" id="mrp" name="mrp" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $mrp;} ?>">
</div> <br>
<div class="inp">
<label for="sellers_price">Seller's Price (₹) : </label>
<input type="text" id="sellers_price" name="sellers_price" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $sellers_price;} ?>">
</div> <br>
<div class="inp">
<label for="last_updated_on">Last Updated on : </label>
<input type="date" id="last_updated_on" name="last_updated_on" value="<?php date_default_timezone_set('Asia/Kolkata'); if((!empty($_POST['submit']))&&($save_vals)){echo $last_updated_on;} else echo date("Y-m-d") ?>">
</div>
</div>
<div class="inp">
<input id="insertButton" type="submit" name="submit" value="Insert">
</div>
<div id="message">
<?php
if(isset($_POST['submit']))
{
$shop = $_POST['shop'];
$category = $_POST['category'];
$item = $_POST['item'];
$qnty = $_POST['qnty'];
$unit = $_POST['unit'];
$price_based_on = $_POST['price_based_on'];
$mrp = $_POST['mrp'];
$sellers_price = $_POST['sellers_price'];
$last_updated_on = $_POST['last_updated_on'];
$result=null;
$dbc = mysqli_connect('localhost','root','atlantis2016','itemDB')
or die("Error Connecting to Database");
$query = "INSERT INTO grocery VALUES ('0', '$shop', '$category', '$item', '$qnty', '$unit', '$price_based_on', '$mrp', '$sellers_price', '$last_updated_on')";
if(!empty($shop)&&!empty($category)&&!empty($item)&&is_numeric($qnty)&&!empty($unit)&&is_numeric($mrp)&&is_numeric($sellers_price)&&!empty($last_updated_on))
{
$result = mysqli_query($dbc, $query)
or die(mysqli_error($dbc));
}
if($result)
{
echo '<span class="success">Item Inserted Successfully!</span>';
$_POST['save_vals']=FALSE;
}
else
{
echo '<span class="failure">Failed to insert Item.</span>';
$_POST['save_vals']=TRUE;
}
}
?>
<script>
$(document).ready(function(){
$("#message").fadeIn(400);
});
</script>
</div>
</form>
</div>
</body>
</html>
I'm trying to determine whether to load the previously posted values if the operation was unsuccessful - otherwise not. If i were to simply set the value of $save_vals at the end of the script, they wouldn't exist at the beginning the next time the page is loaded. So I tried manually setting $_POST['save_vals'] so that it is available the next time the page is loaded. But I get the error:
Notice: Undefined index: save_vals in E:\wamp\www\SomuFinance\insertItem.php on line 27
Line 27 is : $save_vals = $_POST['save_vals'];
What am I doing wrong? How do I ensure that the previous values are loaded ONLY IF the insertion was unsuccessful?
EDIT : While the use of a hidden input type solves the undefined problem, how do I ensure that the form is refilled ONLY when the insertion failed the last time?
Here's my updated code after using an input of hidden type:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Insert Item - SomuFinance</title>
<link rel="stylesheet" type="text/css" href="indexStyle.css">
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
</head>
<body>
<div id="addItemContainer">
<h1>Insert Item</h1>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<div class="leftAligned">
<?php
$save_vals = FALSE;
if(!empty($_POST['submit']))
{
$shop = $_POST['shop'];
$category = $_POST['category'];
$item = $_POST['item'];
$qnty = $_POST['qnty'];
$unit = $_POST['unit'];
$price_based_on = $_POST['price_based_on'];
$mrp = $_POST['mrp'];
$sellers_price = $_POST['sellers_price'];
$last_updated_on = $_POST['last_updated_on'];
$save_vals = $_POST['save_vals'];
}
?>
<div class="inp">
<label for="shop">Shop : </label>
<input type="text" id="shop" name="shop" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $shop;} ?>">
</div> <br>
<div class="inp">
<label for="category">Category : </label>
<input type="text" id="category" name="category" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $category;} ?>">
</div> <br>
<div class="inp">
<label for="item">Item : </label>
<input type="text" id="item" name="item" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $item;} ?>">
</div> <br>
<div class="inp">
<label for="qnty">Quantity : </label>
<input type="text" id="qnty" name="qnty" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $qnty;} ?>">
</div> <br>
<div class="inp">
<label for="unit">Unit : </label>
<input type="text" id="unit" name="unit" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $unit;} ?>">
</div> <br>
<div class="inp">
<label for="price_based_on">Price based on : </label>
<select name="price_based_on" id="price_based_on">
<option value="kilos" <?php if((!empty($_POST['submit']))&&($save_vals)){if($price_based_on=='kilos'){echo 'selected';}} ?>>Kilos</option>
<option value="packet" <?php if((!empty($_POST['submit']))&&($save_vals)){if($price_based_on=='packet'){echo 'selected';}} ?>>Packet</option>
<option value="bottle" <?php if((!empty($_POST['submit']))&&($save_vals)){if($price_based_on=='bottle'){echo 'selected';}} ?>>Bottle</option>
<option value="box" <?php if((!empty($_POST['submit']))&&($save_vals)){if($price_based_on=='box'){echo 'selected';}} ?>>Box</option>
<option value="piece" <?php if((!empty($_POST['submit']))&&($save_vals)){if($price_based_on=='piece'){echo 'selected';}} ?>>Piece</option>
</select>
</div> <br>
<div class="inp">
<label for="mrp">MRP (₹) : </label>
<input type="text" id="mrp" name="mrp" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $mrp;} ?>">
</div> <br>
<div class="inp">
<label for="sellers_price">Seller's Price (₹) : </label>
<input type="text" id="sellers_price" name="sellers_price" value="<?php if((!empty($_POST['submit']))&&($save_vals)){echo $sellers_price;} ?>">
</div> <br>
<div class="inp">
<label for="last_updated_on">Last Updated on : </label>
<input type="date" id="last_updated_on" name="last_updated_on" value="<?php date_default_timezone_set('Asia/Kolkata'); if((!empty($_POST['submit']))&&($save_vals)){echo $last_updated_on;} else echo date("Y-m-d") ?>">
</div>
<input type="hidden" id="save_vals" name="save_vals">
</div>
<div class="inp">
<input id="insertButton" type="submit" name="submit" value="Insert">
</div>
<div id="message">
<?php
if(isset($_POST['submit']))
{
$shop = $_POST['shop'];
$category = $_POST['category'];
$item = $_POST['item'];
$qnty = $_POST['qnty'];
$unit = $_POST['unit'];
$price_based_on = $_POST['price_based_on'];
$mrp = $_POST['mrp'];
$sellers_price = $_POST['sellers_price'];
$last_updated_on = $_POST['last_updated_on'];
$result=null;
$dbc = mysqli_connect('localhost','root','atlantis2016','itemDB')
or die("Error Connecting to Database");
$query = "INSERT INTO grocery VALUES ('0', '$shop', '$category', '$item', '$qnty', '$unit', '$price_based_on', '$mrp', '$sellers_price', '$last_updated_on')";
if(!empty($shop)&&!empty($category)&&!empty($item)&&is_numeric($qnty)&&!empty($unit)&&is_numeric($mrp)&&is_numeric($sellers_price)&&!empty($last_updated_on))
{
$result = mysqli_query($dbc, $query)
or die(mysqli_error($dbc));
}
if($result)
{
echo '<span class="success">Item Inserted Successfully!</span>';
$_POST['save_vals']=FALSE;
}
else
{
echo '<span class="failure">Failed to insert Item.</span>';
$_POST['save_vals']=TRUE;
}
}
?>
<script>
$(document).ready(function(){
$("#message").fadeIn(400);
});
</script>
</div>
</form>
</div>
</body>
</html>
$_POST isn't persistent between loads, the same as $save_vals, it only contains elements submitted by the form. So you would either need to add an input to the form with <input type="hidden" name="save_vals" value="<?php echo $save_vars; ?>"> or use session variables e.g. $_SESSION['save_vars']

Post is not Updating

I am currently trying to make a type blog site and I'm having trouble uploading the post in the edition of a post already created .
I'm currently using the Bootstrap and do not know if this will influence my code or not but the php error is in the lines of the form table.
<?php
include("includes/connect.php");
if (isset($_GET['edit'])) {
$edit_id = $_GET['edit'];
$edit_query = "select * from posts where post_id='$edit_id'";
$run_edit = mysql_query($edit_query);
while ($edit_row=mysql_fetch_array($run_edit)) {
$post_id = $edit_row['post_id'];
$post_title = $edit_row['post_title'];
$post_author = $edit_row['post_author'];
$post_keywords = $edit_row['post_keywords'];
$post_image = $edit_row['post_image'];
$post_content = $edit_row['post_content'];
}
}
?>
<div class="col-md-10" id="content-area">
<div class="container">
<div class="row">
<h2>Edit Post</h2>
<form method="post" action="edit_post.php?edit_form=<?php echo $edit_id ?>" enctype="multipart/form-data">
<fieldset class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" id="title" placeholder="title" value="<?php echo $post_title; ?>">
</fieldset>
<fieldset class="form-group">
<label for="author">Author</label>
<input type="text" name="author" class="form-control" id="author" placeholder="author" value="<?php echo $post_author; ?>">
</fieldset>
<fieldset class="form-group">
<label for="keywords">Keywords</label>
<input type="text" name="keywords" class="form-control" id="keywords" placeholder="keywords" value="<?php echo $post_keywords; ?>">
</fieldset>
<fieldset class="form-group">
<label for="image">Image</label>
<input type="file" name="image" class="form-control" id="image" placeholder="image">
<img src="../images/<?php echo $post_image; ?>" width="100" height="100">
</fieldset>
<fieldset class="form-group">
<label for="content">Content</label>
<textarea name="content" cols="20" rows="20" class="form-control" id="content" placeholder="content"><?php echo $post_content; ?></textarea>
</fieldset>
<input class="btn btn-primary" type="submit" name="submit" value="Update Post"></input>
</form>
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
</html>
<?php
if (isset($_POST['update'])) {
$update_id = $_GET['edit_form'];
$post_title1 = $_POST['title'];
$post_date1 = date('m-d-y');
$post_author1 = $_POST['author'];
$post_keywords1 = $_POST['keywords'];
$post_content1 = $_POST['content'];
$post_image1 = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
if($post_title1=='' or $post_author1=='' or $post_keywords1=='' or $post_content1=='' or $post_image1=='') {
echo "<script>alert('Preencha todos os campos')</script>";
exit();
}
else {
move_uploaded_file($image_tmp, "../images/$post_image1");
$update_query = "update posts set post_title='$post_title1',post_date='$post_date1',post_author='$post_author1',post_image='$post_image1',post_keywords='$post_keywords1',post_content='$post_content1' where post_id='update_id'";
if (mysql_query($update_query)) {
echo "<script>alert('O seu post foi atualizado')</script>";
echo "<script>window.open('view_posts.php','_self')</script>";
}
}
}
?>
First of all, you should prevent SQL Injection.
Change this line:
$edit_id = $_GET['edit'];
To this:
$edit_id = (int)$_GET['edit'];
This way, php will always assume that the variable is an int.
The same on update code:
$update_id = $_GET['edit_form'];
To:
$update_id = (int)$_GET['edit_form'];
And then, you forgot to put $ inside SQL query, on update_id variable to run as a PHP variable:
$update_query = (...) where post_id='$update_id'";

Form won't submit info to database

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('','','');

PHP form processing and validation is not working

I have the following code for my form, and it doesn't seem to work, the query does not insert after all the fields have been filled. I'll really appreciate it if someone can look at it and help me correct any mistake. The method for the form is post and the action is <?php echo $_SERVER['PHP_SELF'];?>. This is my first code in PHP so kind of new here Thanks.
<?php
$counter=1;
if (isset($_POST["post"])) {
$gender= $_POST['gender'];
$fname= $_POST['fname'];
$lname= $_POST['lname'];
$email= $_POST['email'];
$fone= $_POST['fone'];
$school= $_POST['skuul'];
$other= $_POST['other'];
$output_form=false;
$is_error = false;
if (empty($email)) {
echo "Please enter your email or contact info. \n";
$output_form = $is_error = true;
}
if (empty($lname)) {
echo "Please enter your email or contact info. \n";
$output_form= $is_error = true;
}
if (empty($fone)) {
echo "Please enter your email or contact info. \n";
$output_form= $is_error = true;
}
if (empty($fname)) {
echo "Please enter your name. \n";
$output_form= $is_error = true;
}
if ($output_form) {
$query= "INSERT INTO 'elect_conference' ('gender', 'fname', 'lname', 'phone', 'email', 'School', 'course', 'other')".
"values ('$gender', '$fname', '$lname', '$fone', '$email', '$school', '$course', '$other');";
$result = execute($query);
echo '<article class="extra-wrap">'."Hello $name congratulations, you are the number $counter member registered for the ELECT Conference.
A confirmation will be sent to your email ($email) within five(5) hours.\n
Thank you. And have a nice day.</artice>";
$fname="";
$lname="";
$fone="";
$email="";
$fone="";
$school="";
$subject="";
$counter++;
} else {
echo "Please ensure that all the fields are approprietly filled";}
} else {
$output_form=true;
}
if ($output_form) {
?>
<body id="page2">
<!--==============================header=================================-->
<section id="content">
<div class="pad">
<div class="main">
<article class="grid_9 suffix_1">
<div class="form1">
<div class="padding">
<h4 class="border-bot2 img-indent-bot" align="center" style="color:#00C !important">
ELECT Conference <br/>Registration
</h4>
<form id="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"enctype="multipart/form-data">
<fieldset>
<div style="margin-left:90px !important;"><?php echo "$counter/500"; ?></div>
<div class="rowElem0">
<span class="radio">Personal Infomation:</span>
<span class="radio2">
<input type="radio" name="gender" value="Mr" checked>
<label class="ratio">Mr</label>
<input type="radio" name="gender" value="Mrs">
<label class="ratio">Ms</label>
<input type="radio" name="gender" value="Mrs">
<label class="ratio">Mrs</label>
</span>
</div>
<div class="rowElem">
<label><span class="input">First Name:</span></label>
<input type="text" name="fname" value="<?php echo $fname; ?>"/>
</div>
<div class="rowElem">
<label><span class="input">Last Name:</span></label>
<input type="text" name="lname" value="<?php echo $lname; ?>"/>
</div>
<div class="rowElem">
<label><span class="input">Phone:</span></label>
<input type="text" name="fone" value="<?php echo $fone; ?>"/>
</div>
<div class="rowElem">
<label><span class="input">E-mail:</span></label>
<input type="text" name="email" value="<?php echo $email; ?>"/>
</div>
<div class="rowElem1">
<input type="radio" name="graduate" id="chbox4" checked>
<strong><label class="check2">Graduate?</label></strong>
</div>
<div class="rowElem">
<label><span class="input">School:</span></label>
<input type="text" name="skuul" value="<?php echo $school; ?>"/>
</div>
<div class="rowElem">
<label><span class="input">Course:</span></label>
<input type="text" name="course" value="<?php echo $school; ?>"/>
</div>
<div class="rowElem1">
<input type="radio" name="other" id="chbox5">
<strong><label class="check2">Other</label></strong>
<label><span class="input">Specify:</span></label>
<input type="text" name="other" value="<?php echo $other; ?>"/>
</div>
<div class="buttons">
<input class="button" type="submit" value="Submit" />
</div>
</fieldset>
</form>
</div>
</div>
</article>
</div>
</div>
</div>
</section>
<script type="text/javascript"> Cufon.now(); </script>
</body>
<?php
}
?>
</html>
Please show the form code, and be specific in the outcome of the form processing. What exactly didn't work?
In the mean time here are a couple of observations:
Instead of assigning each $_POST element at a time you can do this:
foreach ($_POST as $key=>$value) $$key = $value;
*$output_form* and *$is_error* always have the same value, why the duplication?

Categories