Problem with showing image from the database - php

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

Related

update not working without any error i am using php and sql

I want to update my form using PHP and SQL but update query not working. select query working but update not working. there is no error. when I am using a select query for show value in the input field and it's working. I am trying much think but not figure out what is the error. I am trying much think but not figure out what is the error.
<?php
include 'connection.php';
include 'config.php';
if (isset($_GET['edit'])) {
{
$topHeading=$_POST['topHeading'];
$mainHeading=$_POST['mainHeading'];
$bottomHeading=$_POST['bottomHeading'];
$filesname = $_FILES['file']['name'];
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif","svg");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Convert to base64
$image_base64 = base64_encode(file_get_contents($_FILES['file']['tmp_name']) );
$images = 'data:image/'.$imageFileType.';base64,'.$image_base64;
$sql = "update banner set topHeading='$topHeading', filesname='$filesname', images='$images', mainHeading='$mainHeading', bottomHeading='$bottomHeading' where id='$id'";
if (mysqli_query($connection, $sql)) {
echo "Done";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
// mysqli_close($connection);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$filesname);
if($sql)
{
echo "";
}
else
{
echo "<script>alert('Data not inserted');</script>";
}
}
}
}
$query = mysqli_query($connection, "select * from banner");
while ($row = mysqli_fetch_array($query)) {
echo "<b><a href='editbanner.php?id={$row['id']}'>{$row['topHeading']}</a></b>";
echo "<br />";
}
if (isset($_GET['edit'])) {
echo '<div class="form" id="form3"><br><br><br><br><br><br>
<Span>Data Updated Successfuly......!!</span></div>';
}
?>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$count = 0;
$mysqli = mysqli_query($connection,"SELECT * FROM banner");
foreach($mysqli as $row){
$count++;
?>
<form class="form-horizontal" method="post" name="form1" id="form1" enctype="multipart/form-data">
<div class="form-group label-floating form-rose">
<label for="brandname" class="control-label col-xs-2">Brand Name of Stock Broker</label>
<div class="col-xs-12">
<input type="text" name="topHeading" id="brandname" class="form-control" value="<?php echo $row["topHeading"]; ?>"/>
<span class="error" id="pointfn"></span>
</div>
</div>
<div class="form-group label-floating form-rose">
<label for="name" class="control-label col-xs-2">Contact Person</label>
<div class="col-xs-12">
<input type="text" name="mainHeading" id="name" class="form-control" value="<?php echo $row["mainHeading"]; ?>"/>
<span class="error" id="pointln"></span>
</div>
</div>
<div class="form-group label-floating form-rose">
<label for="designation" class="control-label col-xs-2">Designation</label>
<div class="col-xs-12">
<input type="text" name="bottomHeading" id="designation" class="form-control" value="<?php echo $row["bottomHeading"]; ?>"/>
<span class="error" id="designationln"></span>
</div>
</div>
<div class="label-floating form-rose file-upload">
<div class="file-select">
<div class="file-select-button" id="fileName">Upload Logo</div>
<div class="file-select-name" id="noFile">No file chosen...</div>
<input type="file" name="file" id="chooseFile" required>
</div>
</div>
<div class="form-group label-floating form-rose">
<div class="col-xs-12"> <input type='checkbox' name='checkbox' id="checkbox" required /> <label for="checkbox" class="col-xs-10 term">I accept the terms and condition</label>
</div>
</div>
<button type="submit" name="edit" value="Submit" id="formT" class="button-cta cta btn" onClick="return validateForm()"> I am Interested!</button>
</form>
<?php }} ?>
</body>
</html>
$id is missing above your update query...
$id = $_REQUEST['id'];
$sql = "update banner set topHeading='$topHeading', filesname='$filesname', images='$images', mainHeading='$mainHeading', bottomHeading='$bottomHeading' where id='$id'";

Issue when trying to update clients info

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

php script change when submitting a form data

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.

storing images to folder in php without seperate upload button

i am newbie in php kindly pardon me if i am silly .
I have a form which on submit updates the changes in the form .
Now i added a image upload field with field type as file . my question is i don't want it to be uploaded by clicking upload button separately, instead i want to use the same old submit button which i use for form update . i tried several ways but failed . also i want to save only in the name admin and it should allow only .jpg extension
My form page code is as follows
<?php
if(isset($_POST['update'])) {
$info = pathinfo($_FILES['imagefile']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "admin.".$ext;
$target = WEB_URL .'img/'.$newname;
move_uploaded_file( $_FILES['imagefile']['tmp_name'], $target);
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
// echo "Updated data successfully\n";
}
$result = mysql_query("SELECT * FROM admin where aid='$update_id' ",$link);
while($row = mysql_fetch_array($result)){
$name = $row['a_name'];
$email = $row['a_email'];
$password = $row['password'];
}
mysql_close($link);
?>
<div class="box box-widget widget-user-2">
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<?php echo '<img src="' . $img . '" class="img-circle" alt="User Image">'; ?>
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo "$name"; ?></h3>
<h5 class="widget-user-desc"><?php echo "$role"; ?></h5>
</div>
<div class="box-footer no-padding">
<form role="form" method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo $email; ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo $password; ?>">
</div>
<div class="form-group">
<label for="exampleInputFile">Profile picture</label><br/>
<img id="preview" src="<?php echo $img; ?>" /><br/><br/>
<input type="file" onchange="readURL(this);" id="exampleInputFile" name="imagefile">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
The lines which i tried and failed to achieve my requirement is as follows . which is also there in the above code .
$info = pathinfo($_FILES['imagefile']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "admin.".$ext;
$target = WEB_URL .'img/'.$newname;
move_uploaded_file( $_FILES['imagefile']['tmp_name'], $target);
You forgot to write enctype="multipart/form-data" into your <form> without this attribute you can not upload any image.
You should change :
<form role="form" method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">

Submit button won't work in PHP

PHP Code
<?php
if (!isset($_SESSION)) { session_start(); }
include "connect.php";
include "functions.php";
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
header('location: no_acces.php');
exit();
} else {
$id_user = $_SESSION['userid'];
$q_user = mysqli_query($conn, "SELECT * FROM users WHERE id = $id_user");
if (mysqli_num_rows($q_user) === 1) {
$r_user = mysqli_fetch_assoc($q_user);
} else {
unset($_SESSION['login']);
unset($_SESSION['userid']);
header('location: no_acces.php');
exit();
}
}
$error = "";
$userQuery = mysqli_query($conn, "SELECT username FROM users");
$user = mysqli_fetch_assoc($userQuery);
$id = $_GET['id'];
if (isset($_POST['edit_contact'])) {
$roepnaam = $_POST['roepnaam'];
$naam = $_POST['naam'];
$land = $_POST['land'];
$bedrijf = $_POST['bedrijf'];
$adres1 = $_POST['adres1'];
$adres2 = $_POST['adres2'];
$stad = $_POST['stad'];
$postcode = $_POST['postcode'];
$provincie = $_POST['provincie'];
$telefoon = $_POST['telefoon'];
$email = $_POST['email'];
$captcha= $_POST['g-recaptcha-response'];
if(!$captcha){
$error = "Er is een fout opgetreden";
}
if ($error == "") {
$insertUser = ("UPDATE address SET
roepnaam = '$roepnaam', naam = '$naam', bedrijf = '$bedrijf', telefoon = '$telefoon', email = '$email', adres1 = '$adres1', adres2 = '$adres2', stad = '$stad', postcode = '$postcode', provincie = '$provincie', land = '$land' WHERE id = $id");
if (mysqli_query($conn, $insertUser)) {
$_SESSION['edit_contact'] = true;
header('location: address_book.php');
} else {
$error = "Er is een fout opgetreden";
}
}
}
?>
HTML Code
<!DOCTYPE html>
<html lang="en">
<body>
<form action="" method="post">
<?php if ($error !== "") { ?>
<div class="row">
<div class="col-md-12 error">
<?php echo $error; ?>
</div>
</div>
<?php } ?>
<label for="firstName" class="control-label">Naam:</label>
<div class="row ">
<div class="col-md-6">
<input type="text" class="form-control" id="firstName" placeholder="Roepnaam" name="roepnaam" value="<?php if (isset($_POST['roepnaam'])) { echo $_POST['roepnaam']; } ?>" required/>
</div>
<div class="col-md-6">
<input type="text" class="form-control" id="lastName" placeholder="Naam" name="naam" value="<?php if (isset($_POST['naam'])) { echo $_POST['naam']; } ?>" required/>
</div>
</div>
<label for="username" class="control-label">Bedrijf:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="username" placeholder="Bedrijf" name="bedrijf" value="<?php if (isset($_POST['bedrijf'])) { echo $_POST['bedrijf']; } ?>" required/>
</div>
</div>
<label for="password" class="control-label">Telefoonnummer:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="password" placeholder="Telefoonnummer" name="telefoon" value="<?php if (isset($_POST['telefoon'])) { echo $_POST['telefoon']; } ?>" required/>
</div>
</div>
<label for="email" class="control-label">Email:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="email" placeholder="E-mailadres" name="email" value="<?php if (isset($_POST['email'])) { echo $_POST['email']; } ?>" required/>
</div>
</div>
<label for="adres1" class="control-label">Adres:</label>
<div class="row">
<div class="col-md-12">
<input type="text" class="form-control" id="adres1" placeholder="Adres 1" name="adres1" value="<?php if (isset($_POST['adres1'])) { echo $_POST['adres1']; } ?>" required/>
</div>
</div>
<div class="row padding-top-10">
<div class="col-md-12">
<input type="text" class="form-control" id="adres2" placeholder="Adres 2" name="adres2" value="<?php if (isset($_POST['adres2'])) { echo $_POST['adres2']; } ?>"/>
</div>
</div>
<div class="row">
<div class="col-md-3">
<label for="postcode" class="control-label">Postcode:</label>
</div>
<div class="col-md-5">
<label for="city" class="control-label">Stad:</label>
</div>
<div class="col-md-4">
<label for="regio" class="control-label">Regio:</label>
</div>
</div>
<div class="row ">
<div class="col-md-3">
<input type="text" class="form-control" id="postcode" placeholder="Postcode" name="postcode" value="<?php if (isset($_POST['postcode'])) { echo $_POST['postcode']; } ?>" required/>
</div>
<div class="col-md-5">
<input type="text" class="form-control" id="city" placeholder="Stad" name="stad" value="<?php if (isset($_POST['stad'])) { echo $_POST['stad']; } ?>" required/>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="regio" placeholder="Provincie" name="provincie" value="<?php if (isset($_POST['provincie'])) { echo $_POST['provincie']; } ?>" required/>
</div>
</div>
<label for="land" class="control-label">Land:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="password" placeholder="Land" name="land" value="<?php if (isset($_POST['land'])) { echo $_POST['land']; } ?>" required/>
</div>
</div>
<div class="row">
<div class="col-md-8 padding-top-10 ">
<div class="g-recaptcha " data-sitekey="6LcCsBoTAAAAAK72uzyJSrgWwD8xuF6jFIfgFaHX"></div>
</div>
</div>
<div class="row">
<div class="col-md-2 padding-top-10">
<input type="submit" name="edit_contact" class="btn btn-succes" value="Wijzigen">
</div>
<div class="col-md-2 padding-top-10">
<input type="text" name="delete_contact" action="delete_contact.php" class="btn btn-succes" value="Contact verwijderen">
</div>
</div>
</form>
</body>
</html>
PHP Code
<?php
if (!isset($_SESSION)) { session_start(); }
include "connect.php";
include "functions.php";
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true || !isset($_SESSION['userid']) || $_SESSION['userid'] == "") {
header('location: login.php');
exit();
} else {
session_regenerate_id();
}
$id = $_GET['id'];
$query = "DELETE FROM address WHERE id= $id";
mysqli_query ($query);
if (mysql_affected_rows() == 1) {
header('location: addressbook.php');
} else {
echo "Verwijderen mislukt";
}
?>
I'm trying to make a delete button for my contacts within the addressbook. but everytime I click "Contact verwijderen" the webpage resets it self and the contact won't be deleted. Could anyone help me to fix this?
You input is a text input and you don't have a form asociated with it,create one and change the type of submit to submit
<form action="delete_contact.php" method="post">
//other inputs
<input type="submit" name="delete_contact" class="btn btn-succes" value="Contact verwijderen">
</form>
You are mixing MySQL and MySQLi functions:
mysqli_query ($query);
if (mysql_affected_rows() == 1)
You cannot mix MySQL with MySQLi, your code should be:
mysqli_query ($query);
if (mysqli_affected_rows($conn) == 1)
Add a normal link to delete the contact, you don't need a form.
<a href="delete_contact.php?id=<?php echo $id ?>">
Contact verwijderen
</a>

Categories