image does not save in the database in PHP - php

After user log into his profile I am showing his user profile. And there I let him to add his profile picture. After user add his profile picture I want to insert image path to the database.
database at the login-id, username, password, email
database after profile picture save - id, username,password,email,name1(where img path save)
Following code save the picture in the given folder but it does not save the image path in the database.can anybody help me please?
<?php include('header.php');?>
<?php include('config.php');?>
<?php
// index.php
session_start();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
$username = $_SESSION['username'];
$sql = "SELECT * FROM services WHERE user_name = '".$_SESSION['username']."'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<?php
if(isset($_POST['but_upload'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$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");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Insert record
//$query = "insert into services(name1) values('".$name."') where user_name = '".$_SESSION['username']."'";
$query = " UPDATE services SET name1='$name' where user_name = '".$_SESSION['username']."";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
?>
<div class="container">
<div class="row">
<div class="col-md-7 ">
<div class="panel panel-default">
<div class="panel-heading"> <center> <h4 >User Profile</h4></center></div>
<div class="panel-body">
<div class="box box-info">
<div class="box-body">
<div class="col-sm-6">
<div align="center">
<form method="post" action="welcome.php" enctype='multipart/form-data'>
<div class="imageupload panel panel-default">
<div class="file-tab panel-body">
<label class="btn btn-default btn-file">
<span>Browse</span>
<!-- The file is stored here. -->
<input type="file" name="file">
</label>
<button type="button" class="btn btn-default">Remove</button>
</div>
<input type='submit' value='Save name' name='but_upload'>
</div>
</div>
<br>
<!-- /input-group -->
</div>
<div class="col-sm-6">
<h4 style="color:#00b1b1;"><?php echo $row ['name']; ?></h4></span>
<span><p><?php echo $row ['service']; ?></p></span>
</div>
<div class="clearfix"></div>
<hr style="margin:5px 0 5px 0;">

Change
$query = " UPDATE services SET name1='$name' where user_name = '".$_SESSION['username']."";
to
$query = ("UPDATE services SET name1='$name' where user_name = '".$_SESSION['username']."") or die(mysqli_error($con));
I added mysqli_error. It will print errors in the query & brackets

Related

How do I remain the image when I update edit form?

I can update image on my application but if I have to update same picture again and again when I click edit button on edit section...so I want to remain current image when I update edit section without any change for image.
I tried to put these codes below but it didn't work....
if(empty($image)){
$selected_image = $db->prepare("SELECT * FROM posts WHERE post_id={$the_post_id}");
$selected_image->execute(array($the_post_id));
$selected_images = $selected_image->fetch();
}
Does anyone give some advise or concern for my codes?
I really appreciate!
Thank you!
<!-- Edit -->
<?php
if(isset($_REQUEST['edit_post_id'])){
$the_post_id = $_REQUEST['edit_post_id'];
$posted = $db->prepare("SELECT * FROM posts WHERE post_id = $the_post_id ");
$posted->execute(array($the_post_id));
$posted_p = $posted->fetch();
}
?>
<?php
if(isset($_POST['edit_post'])){
$edit_posts = $db->prepare("UPDATE posts SET post_image=?, post_contents=? WHERE post_id ='{$the_post_id}' ");
$edit_posts->execute(array(
$image = date('YmdHis') . $_FILES['image']['name'],
$_POST['post_contents']
));
move_uploaded_file($_FILES['image']['tmp_name'], './images/' . $image);
if(empty($image)){
$selected_image = $db->prepare("SELECT * FROM posts WHERE post_id={$the_post_id}");
$selected_image->execute(array($the_post_id));
$selected_images = $selected_image->fetch();
}
header('Location: index.php');
exit();
}
?>
<!-- Edit form -->
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<div class="well">
<form action="" method="post" enctype="multipart/form-data">
<div>
<label for="summernote">Edit</label>
<textarea class="form-control" name="post_contents" id="summernote" col="30" rows="10"><?php echo htmlspecialchars($posted_p['post_contents'], ENT_QUOTES); ?></textarea>
</div>
<div class="form-group">
<label for="post_image">Image</label>
<input type="file" name="image" >
<img width="100" src="./images/<?php echo $posted_p['post_image']; ?>" >
</div>
<span class="form-group">
<p><input class="btn btn-primary" type="submit" name="edit_post" value="Edit"></p>
</span>
</form>
</div>
</div>
</div>
</div>
you should update your query so it sets post_image only if $_FILES['image'] it exists
this should work:
<?php
if(isset($_POST['edit_post'])){
$image = $_FILES['image'] ? date('YmdHis') . $_FILES['image']['name'] : "";
$edit_posts = $db->prepare(
"UPDATE posts SET post_contents=?". empty($image) ?: ", post_image=?" ."WHERE post_id ='{$the_post_id}' "
);
$params = array(
$_POST['post_contents']
);
if (!empty($image)) {
$params[] = $image;
}
$edit_posts->execute($params);
move_uploaded_file($_FILES['image']['tmp_name'], './images/' . $image);
if(empty($image)){
$selected_image = $db->prepare("SELECT * FROM posts WHERE post_id={$the_post_id}");
$selected_image->execute(array($the_post_id));
$selected_images = $selected_image->fetch();
}
header('Location: index.php');
exit();
}
?>

Default image won't show when database is still empty

Basically, the whole thought here is changing profile pictures and it will be uploaded in the database.
I want to show a default icon first when the database is still empty but my codes just displays a broken image thumbnail. What could have gone wrong?
<form method="post" enctype="multipart/form-data">
<div class="row form-group">
<div class="col col-md-3">
<label for="text-input" class="form-control-label">Profile Picture</label>
</div>
<div class="col-9 col-md-9">
<div class="input-group">
<?php
$query = "SELECT image FROM member WHERE member_id = '$ID'";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result))
{
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'">';
}
} else{
echo "<img src='images/icon.jpg' style='height:200px'draggable='false'>";
}
?>
<div class="col-12">
<input type="file" name="image" id="image" style ='margin-left:-10px;margin-top:5px'>
</div>
<div class="col-12">
<input type="submit" name="insert" id="insert" value="Change Profile Picture" class="btn btn-primary" style ='margin-left:-10px;margin-top:5px'>
</div>
<?php
if(isset($_POST["insert"])){
$file = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$query = "UPDATE member SET image = '$file' WHERE member_id='$ID'";
if(mysqli_query($con, $query)){
echo ("<script LANGUAGE='JavaScript'>
window.alert('Profile Picture has been successfully changed!');
window.location.href='edit.php';
</script>");
}
}
?>
</div>
</div>
</div>
</form>
if your database is empty upload query will not work. if your image row is empty then your code should be like if image row is not empty display image else display the default image.
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)) {
if (isset($row['image']) && !empty($row['image'])) {
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'">';
} else {
echo "<img src='images/icon.jpg' style='height:200px'draggable='false'>";
}
} // endwhile
} else{
echo "no result found";
}
While writing HTML or CSS code inside PHP you should put a \ before all double quotations and you need change all quotations to double quotation.like shown below:
echo "<img src=\"images/icon.jpg\" style=\"height:200px;\" draggable=\"false\">";
I didn't check your PHP codes, If you've coded them properly the problem is obviously what I mentioned.

Date not being stored in database from .xlsx sheet in PHP

I have a page to save an excel sheet records to the database. The records are being stored same way as they are provided in excel sheet other than "date of birth" column.
The "Date of Birth" column saves only for the second record being uploaded from excel sheet. I had been searching a lot on this but not found the exact reason for it.
Here is my complete code ,
<?php include 'blocks/headerInc.php' ;
include 'Classes/PHPExcel/IOFactory.php';
?>
<?php
$scsmsg = "" ;
$errmsg = "" ;
if(isset($_POST['submit']))
{
extract($_POST);
//$moduleId = mysql_real_escape_string(htmlspecialchars(trim($module_id)));die;
if(empty($_FILES['bulk_file']['name']))
{
$errmsg .= 'Please Choose File.<br>';
}
if(!empty($_FILES['bulk_file']['name']))
{
$extensions = array('.xlsx');
$valid_extensions = '.xlsx';
$extension = strrchr($_FILES['bulk_file']['name'], '.');
if (!in_array($extension, $extensions))
{
$errmsg .="Wrong files format , alowed Extension only".$valid_extensions.""."<br>";
}
}
if($errmsg == "")
{
$created = date("Y-m-d h:i:s");
$register_date = date("Y-m-d");
$created_by = $_SESSION['session_admin_id'] ;
$bulk_file = $_FILES['bulk_file']['name'];
if(!empty($bulk_file))
{
$tmp_name=$_FILES['bulk_file']['tmp_name'];
$bulk_file=$_FILES['bulk_file']['name'];
$file_name = $bulk_file;
//$file=$file_name.".csv";
$inputFileName = "uploads/user/$file_name";
$file_sucess=move_uploaded_file($tmp_name,$inputFileName);
//$inputFileName = 'format.xlsx';
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++)
{
$salutation = trim($allDataInSheet[$i]["A"]);
$sbiempid = trim($allDataInSheet[$i]["B"]);
$branch = trim($allDataInSheet[$i]["C"]);
$middlename = trim($allDataInSheet[$i]["D"]);
$firstname = trim($allDataInSheet[$i]["E"]);
$lastname = trim($allDataInSheet[$i]["F"]);
$dateofbirth = trim($allDataInSheet[$i]["G"]);
$dateInput = explode('-',$dateofbirth);
$dob = $dateInput[2].'-'.$dateInput[1].'-'.$dateInput[0];
// $dob ="19".date("Y-m-d", strtotime($dateofbirth));
//var_dump($dob);
//print_r($dob);
$mobileno = trim($allDataInSheet[$i]["H"]);
$email = trim($allDataInSheet[$i]["I"]);
$city = trim($allDataInSheet[$i]["J"]);
$state = trim($allDataInSheet[$i]["K"]);
$designation = trim($allDataInSheet[$i]["L"]);
$corporate_user_sql=mysql_fetch_array(mysql_query("select * from tbl_corporate where id='$created_by'"));
$pre_define_day=$corporate_user_sql['pre_defined_day'];
$dataQuestion = array("type"=>"3","salutation"=>$salutation, "employee_id"=>$sbiempid, "branch"=>$branch, "middle_name"=>$middlename, "first_name"=>$firstname, "last_name"=>$lastname, "dob"=> $dob, "mobile"=>$mobileno, "email"=>$email, "city"=>$city,"state"=>$state,"designation"=>$designation,"created_on"=>$created, "created_by"=>$created_by,"status"=>"0","register_date"=>$register_date,"request_updated_day"=>$pre_define_day,"registration_type"=>"1");
$db->query_insert("tbl_user", $dataQuestion);
$question_id = mysql_insert_id();
$raw_password=uniqid().$question_id;
$md5_pass=md5(uniqid().$question_id);
$dataOption1 = array("registration_id"=>$sbiempid."_".$question_id,"password"=>$md5_pass,"raw_password"=>$raw_password);
$db->query_update("tbl_user", $dataOption1,"id=$question_id");
}
}
$scsmsg = "<b>Record inserted Successfully</b>";
}
}
?>
<div class="container pagecontainer">
<!-- Static navbar -->
<div class="row row-offcanvas row-offcanvas-right">
<!--/.col-xs-12.col-sm-9-->
<div class="col-sm-3 col-md-3 sidebar" id="sidebar">
<div id="left_panel" class="clearfix left">
<?php include 'blocks/leftnavInc.php' ; ?>
</div>
</div>
<div class="col-xs-12 col-sm-9 page-right">
<div class="panel panel-primary">
<div class="panel-heading">Upload User</div>
<div class="panel-body">
<div class="column col-sm-offset-0">
<?php
if($scsmsg!="")
{
echo "<div class='success'>".ucwords($scsmsg)."</div>";
}
if($errmsg!="")
{
echo "<div class='error'>".ucwords($errmsg)."</div>";
}
echo "<div id='error'></div>";
?>
<form class="form-horizontal" method="post" action="" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">Select FIle:</label>
</div>
<div class="col-md-9">
<input type="file" name="bulk_file" class="form-control" required="" >
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">
Download Format</label>
</div>
<div class="col-md-9 text-right">
<button type="submit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Save</button>
<button type="reset" onClick="javascript:window.location.href='quizList.php';" class="btn btn-danger"><i class="glyphicon glyphicon-ban-circle"></i> Cancel</button>
<button type="reset" onclick="javascript:history.go(-1)" class="btn btn-danger"><i class="glyphicon glyphicon-ban-circle"></i> Go Back</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!--/.sidebar-offcanvas-->
</div>
</div>
<?php include 'blocks/footerInc.php'; ?>
May I know where am I doing wrong in this as rest of the data fields are being posted semantically. This stores date of birth only for the second record in the excel sheet and for rest rows date of birth are being saved as 0000-00-00.
Any suggestion and help will be highly appreciated.
I'd suggest that you don't request formatted values when you build the array from the spreadsheet content, use
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,false,true);
instead of
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
Then manually convert the raw timestamp date values from cells to the format you need for the database
$dateofbirth = PHPExcel_Shared_Date::ExcelToPHPObject($allDataInSheet[$i]["G"])
->format('Y-m-d');

Form with textarea and multiple files input option repeats the entry while uploading to database

I've form with two Text areas and a multiple file input field and I need to upload them to database ....
here is my HTML code
<form method="post" action="../php/new-upload.php" enctype="multipart/form-data">
<div id="tabs-1">
<textarea placeholder="Hi" name="n_head" class="n_head"></textarea>
<textarea placeholder="Story..." name="n_st" class="n_st"></textarea>
<div class="tg-it">
<div class="tg-it-hd">Add Tag:</div>
<input name="tags" id="singleFieldTags2" value="Election, Namo">
</div>
</div>
<div id="tabs-2" class="new-post-det">
<div id="upload">
<div id="drop">
Drop Images Here
or
<a>Browse</a>
<input type="file" name="upl[]" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</div>
</div>
<div id="new-ps-bt">
<input type="submit" class="new-ps-bt" value="Post" />
<a id="bk-bt" class="bk-mn" href="../">Back <</a>
</div>
</form>
and here is my new-upload.php file
<?php
include("../config.php");
session_start();
$n_head=$_POST['n_head'];
$n_story=$_POST['n_story'];
$n_up=$_SESSION["user_id"];
$query = "INSERT INTO news(N_headline,N_story,N_U_id)VALUES('$n_head','$n_story','$n_up')";
$data = mysql_query ($query)or die(mysql_error());
$last_id = mysql_insert_id();
foreach ($_FILES['upl']['name'] as $filename) {
$n_img = $_FILES['upl']['tmp_name'];
$query_1 = "INSERT INTO news_img(N_id,ng_img)VALUES('$last_id','$n_img')";
$data_2 = mysql_query ($query_1)or die(mysql_error());
}
if($data)
{
header("Location:../");
}
mysql_close($con);
?>
so the problem is when this form is submitted, the database entry gets repeated the number of times same as the number of photos selected ....
help me out with this problem...
Please change these code in respective place
$n_story = $_POST['n_story'];
foreach ($_FILES['upl']['name'] as $filename) {
$n_img = $filename;
$query_1 = "INSERT INTO news_img(N_id,ng_img)VALUES('$last_id','$n_img')";
$data_2 = mysql_query ($query_1)or die(mysql_error());
}
Hope that fix your problem.

PHP articles and images issue

This is still not working, so I'm posting whole code here now...
<form id="contact-form" action="fileovi/dodaj_novost.php" method="post">
<fieldset>
<div class="coll-1">
<div class="txt-form">Naslov[hr]</div>
<label class="name">
<input type="text" name="naslov_hr">
<br>
</div>
<div class="clear"></div>
<div class="coll-1">
<div class="txt-form">Naslov[en]</div>
<label class="name">
<input type="text" name="naslov_en">
<br>
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="coll-1">
<div class="txt-form">Naslov[de]</div>
<label class="name">
<input type="text" name="naslov_de">
<br>
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="coll-1">
<div class="txt-form">Link slike</div>
<label class="name">
<input type="file" name="image[]" enctype="multipart/form-data"/><br />
<input type="file" name="image[]" enctype="multipart/form-data"/><br />
<br>
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="coll-big">
<div class="txt-form"><center>Tekst[hr]</center></div>
<label class="name">
<textarea id="tekst" name="tekst_hr"></textarea>
<br>
</div>
<div class="clear"></div>
<div class="coll-big">
<div class="txt-form"><center>Tekst[en]</center></div>
<label class="name">
<textarea id="tekst1" name="tekst_en"></textarea>
<br>
</div>
<div class="clear"></div>
<div class="coll-big">
<div class="txt-form"><center>Tekst[de]</center></div>
<label class="name">
<textarea id="tekst2" name="tekst_de"></textarea>
<br>
</div>
<div class="clear"></div>
Dodaj!
</form>
And here's my php function that I've created...
function dodaj_novost()
{
global $mysqli;
$mysqli->query("SET NAMES utf8");
$mysqli->query("SET CHARACTER SET utf8");
$mysqli->query("SET COLLATION_CONNECTION='utf8_general_ci'");
//sanitize variables
$naslovhr = $_POST['naslov_hr'];
$naslovhr = $mysqli->real_escape_string($naslovhr);
$nasloven = $_POST['naslov_en'];
$nasloven = $mysqli->real_escape_string($nasloven);
$naslovde = $_POST['naslov_de'];
$naslovde = $mysqli->real_escape_string($naslovde);
$teksthr = $_POST['tekst_hr'];
$teksthr = $mysqli->real_escape_string($teksthr);
$teksten = $_POST['tekst_en'];
$teksten = $mysqli->real_escape_string($teksten);
$tekstde = $_POST['tekst_de'];
$tekstde = $mysqli->real_escape_string($tekstde);
//sanitize variables END
$dan = date('d');
$mjesec = date('M');
$godina = date('Y');
$sql="INSERT INTO novosti (naslovhr, nasloven, naslovde, teksthr, teksten, tekstde, dan, mjesec, godina) VALUES ($naslovhr,$nasloven, $naslovde,$teksthr,$teksten,$tekstde,$dan,$mjesec,$godina)";
$query = $mysqli->query("$sql");
//Add picture!
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if(isset($_FILES['image'])){
for($i=0; $i<count($_FILES['image']['name']); $i++){
if( #is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
{
// unique file path
$filename = uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path.$filename))
{
$status = $path.$filename;
$link = 'http://'.$domena.'/'.$path.'/'.$filename;
$upit = "INSERT INTO slike_novosti (link, id_posta) VALUES ($link, $id_posta)";
$upit = $mysqli->query("$upit");
if ($upit == 'true'){
echo 'Successfull!';
} else {
echo 'Not sucessfull!';
}
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else{
//image is not uploaded!
$status = ' ';
}
echo '<br>'.$status.'<br>';
}
} else {
echo 'Nema slike!';
}
//Add picture END!!
}
And for some reason this code is still not working, If someone can point me in right direction on how to solve this problem.. I would be soo happy! :) Cheers.
At first:
$sql1 = "INSERT INTO slike_novosti (slika, link_slike) VALUES ('$link_slike','$slika')";
check order of your variables? I think, it must be:
$sql1 = "INSERT INTO slike_novosti (slika, link_slike) VALUES ('$slika','$link_slike')";
at second: Use PDO component, you have a very bad code and SQL Injection.
Remove the single qoutes from your $variables. For PHP '$var' is a variable with the value of $var. If you want them qouted, use "$var". See variables
So this wil work
$sql="INSERT INTO novosti (naslovhr, nasloven, naslovde, teksthr, teksten, tekstde,
link_slike, dan, mjesec, godina) VALUES
$naslovhr,$nasloven,$naslovde,$teksthr,
$teksten,$tekstde,$link_slike,$dan,$mjesec,$godina)";

Categories