I have an upload image to database code like this:
<form method="post" action="quanly.php" class="form-group justify-content-center" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="image" name="image">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<div class="col text-center">
<button type="submit" name="submit" id="add_btn" class="btn btn-primary mb-2"> <i class="fas fa-plus"></i>Submit</button>
</div>
</form>
And the PHP code:
$image = addslashes($_FILES['image']['name']);
$query = "INSERT INTO tasks (image) VALUES ('$image')";
mysqli_query($db, $query); //db is the mysql connection
Everything upload works just fine, but I have some code to display image using Bootstrap 4 modal
<?php $i = 1; while ($row = mysqli_fetch_array($tasks)) { ?>
<button type="button" class="btn btn-primary btn-sm " data-toggle="modal" data-target="#imagemodal<?php echo $row['id'];?>" <?php if (empty($row['image'])) { echo "disabled"; } ?> ><i class="fas fa-image"></i></button>
<!-- IMAGE MODAL BEGIN -->
<div class="modal fade" id="imagemodal<?php echo $row['id'];?>">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Xem ảnh/ đính kèm</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>'; ?>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- IMAGE MODAL END -->
<?php $i++; } ?>
Which image of rows showing a small image square (error), when I view the image url, it's something like this: data:image/jpeg;base64,ei5wbmc=
Store and upload image in folder code
<?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 images(name) values('".$name."')";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
?>
<form method="post" action="" enctype='multipart/form-data'>
<input type='file' name='file' />
<input type='submit' value='Save name' name='but_upload'>
</form>
Show in display view.
<?php
$sql = "select name from images where id=1";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$image = $row['name'];
$image_src = "upload/".$image;
?>
<img src='<?php echo $image_src; ?>' >
Related
I want to update my profile image but I don't know how to update it. I successfully insert it into my database and folder but when user wants to update it So I don't know how to update this image. Can you tell me how this is possible? Thanks.
Code of my HTML form
<form class="form" action="accountsetting.php" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-12 col-sm-auto mb-3">
<div class="mx-auto" style="width: 140px;">
<div class="rounded-circle avatar avatar-xl mb-3">
<img class="rounded-circle" id="preview_avatar" name="avatar" src="<?php echo
$_SESSION['user']['avatar']; ?>" width="100" height="100">
</div>
</div>
</div>
<div class="col d-flex flex-column flex-sm-row justify-content-between mb-3">
<div class="text-center text-sm-left mb-2 mb-sm-0">
<h4 class="pt-sm-2 pb-1 mb-0 text-nowrap"><?php echo $_SESSION['user']['fullname']; ?></h4>
<p class="mb-0"><?php echo $_SESSION['user']['username']; ?></p>
<div class="form-group mb-2 pt-2">
<input class='input' type='hidden' name='id' value="<?php echo $_SESSION['user']['id']; ?>" />
<input id="avatar" type="file" name="avatar" hidden="" accept="image/png, image/jpeg,
image/jpg">
<button id="uploadBtn" type="submit" name="profile" class="btn btn-primary btn-file " ><i
class="fa fa-camera" aria-hidden="true"></i>   Upload Avatar</button>
</div>
<div class="row">
<div class="col d-flex justify-content-end pr-5">
<button class="btn btn-primary " type="submit" name="profileupdate">Save Changes</button>
</div>
</div>
</div>
</div>
</div>
</form>
Code of my PHP side
// sava image into directoray
$id="";
$filename = $avatar['name'];
$fileerror = $avatar['error'];
$filetmp = $avatar['tmp_name'];
$fileext = explode('.',$filename);
$filecheck = strtolower(end($fileext));
$fileextstored =array('png', 'jpg', 'jpeg');
$destinationfile = 'upload/';
$destinationfile = $destinationfile .$filename;
$destinationfile1 = 'userside/upload/';
$destinationfile1 = $destinationfile1 .$filename;
try {
//throw exception if can't move the file
if (!move_uploaded_file($filetmp, $destinationfile)) {
throw new Exception('Could not move file');
}
if(!copy ( $destinationfile , $destinationfile1 ))
{
throw new Exception('Could not move 2nd file');
}
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
// image insert
if(in_array($filecheck, $fileextstored))
{
$query = "INSERT INTO users (avatar) VALUES('$destinationfile')";
$displayquery = "select * from users where id= $id";
$displayquery = mysqli_query($db,$displayquery);
}
What's type of code i will use. When the user click on the save button the image will successfully update.
It looks like you need a condition in your INSERT INTO statement. Shouldn't you insert the avatar in the users table where id = $id?
Here:
"INSERT INTO users (avatar) VALUES('$destinationfile')";
Change to:
"INSERT INTO users (avatar) VALUES('$destinationfile') WHERE id = $id";
Update: if you're inserting the path to the image, then maybe you need to put the URL in with the image tag:
<!-- insert code for http or https:// -->
<img class="rounded-circle" id="preview_avatar" name="avatar" src="<?php echo "http://" . $_SERVER['SERVER_NAME'] . "/" . $_SESSION['user']['avatar']; ?>" width="100" height="100">
This relies on that path being valid and accessible from the server name, like http://localhost/uploads/image_name.jpg if the path is .../uploads/image_name.jpg. You can put the path in the session variable, then just add the image name on the end, e.g. $_SESSION['image_path'] = 'http://localhost/uploads/'.
The "if(isset($_POST["titleId"]) && !empty($_POST["titleId"])" in my code is returning false value.
I'm working on a CRUD application, the insert modal is working fine, now I'm stuck at the update part of it. So when you click on the update icon it does fetch the right titleId in the URL but the first 'if' condition returns false and hence the update isn't working.
Here's what I've tried so far.
admin.php
<?php
$typeId = filter_input(INPUT_GET, "type");
$titleId = filter_input(INPUT_GET, "titleId");
$active = "admin" . $typeId;
require_once './pages/header.php';
require_once './functions/queries.php';
$getAll = Queries::getAllTitle($typeId);
?>
<div class="container">
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header clearfix">
<h2 class="pull-left"></h2>
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>
</div>
<!--<div class="container">
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>
<br><br>-->
<div class="panel-group" id="titleAccordion">
<?php
for ($i = 0; $i < count($getAll); $i++) {
echo <<<HTML
<div class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title">
<a data-toggle="collapse" data-parent="#titleAccordion" href="#collapseF{$i}">{$getAll[$i]['title']}</a></h4>
</div>
<div id="collapseF{$i}" class="panel-collapse collapse" >
<div class="panel-body">
<div class="table-responsive">
<table class="table table-condensed"><tbody>
<tr><td>Title:</td><td>{$getAll[$i]['title']}</td></tr>
<tr><td>Units:</td><td>{$getAll[$i]['units']}</td></tr>
<tr><td>Category:</td><td>{$getAll[$i]['category']}</td></tr>
<tr><td>
<tr><td><input type="hidden" id="titleId" name="titleId" value="{$getAll[$i]['titleId']}"> </tr><td>
<a href='edit.php?titleId={$getAll[$i]['titleId']}' title='Update Record' data-toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>
<a href='delete.php?titleId={$getAll[$i]['titleId']}' title='Delete Record' data-toggle='tooltip'><span class='glyphicon glyphicon-trash'></span></a>
</tr></td>
</tbody></table>
</div>
</div>
</div>
</div>
HTML;
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Title Add Modal-->
<div class="modal fade" id="facultyAddModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Title</h4>
</div>
<div class="modal-body">
<div id="adminResult" class="hide" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<div id="resultAdminContent"></div>
</div>
<form class="cmxform" id="adminForm" method="post">
<label for="Activity">ActivityAttended (required)</label>
<input class="form-control" id="adminTitle" name="title" type="text" required>
<br>
<label for="units">Units (required)</label>
<input class="form-control" id="adminUnits" type="number" name="units" required>
<br>
<label for="Category">Category (Optional)</label>
<input class="form-control" id="adminCategory" type="text" name="category">
<br>
<?php echo
'<input type="hidden" id="addadminTypeId" value="'.$typeId.'">';
?>
<?php echo
'<input type="hidden" id="titleId" name="titleId" value="'.$titleId.'">';
?>
<button class="btn btn-info btn-primary" type="submit">Submit</button>
<br>
<br>
</form>
</div>
</div>
</div>
</div>
update.php
<?php
require_once 'functions/db_connection.php';
$conn = DB::databaseConnection();
$title = $units = $category = "";
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
$titleId = $_POST['titleId'];
$sql = "UPDATE title SET title = :title, units = :units, category = :category WHERE titleId = :titleId";
if($stmt = $conn->prepare($sql))
{
// Bind variables to the prepared statement as parameters
$stmt->bindParam(':titleId', $titleId);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':units', $units);
$stmt->bindParam(':category', $category);
if ($stmt->execute()) {
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
unset($stmt);
}
unset($conn);
} else{
if(isset($_GET["titleId"]) && !empty(trim($_GET["titleId"]))){
$titleId = trim($_GET["titleId"]);
$sql = "SELECT * FROM title WHERE titleId = :titleId";
if($stmt = $conn->prepare($sql))
{
$stmt->bindParam(':titleId', $titleId);
if ($stmt->execute()){
if($stmt->rowCount() == 1){
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Retrieve individual field value
$title = $result["title"];
$units = $result["units"];
$category = $result["category"];
} else{
echo"error1";
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
unset($stmt);
unset($conn);
} else{
// URL doesn't contain id parameter. Redirect to error page
echo"error2";
exit();
}
}
?>
<!--<!DOCTYPE html>-->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Update Record</h2>
</div>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<label for="Activity">Title</label>
<input class="form-control" id="adminTitle" name="title" type="text" value="<?php echo $title; ?>" required>
<br>
<label for="units">Units (required)</label>
<input class="form-control" id="adminUnits" type="number" name="units" value="<?php echo $units; ?>" required>
<br>
<label for="Category">Category (Optional)</label>
<input class="form-control" id="adminCategory" type="text" value="<?php echo $category; ?>" name="category">
<br>
<input type="hidden" name="titleId" value="<?php echo $titleId; ?>">
<button class="btn btn-info btn-primary" type="submit">Submit</button>
<br>
<br>
</form>
</div>
</<div>
</div>
</div>
</div>
</body>
</html>
The only goal here is to get the update form working, the user should be able to update the records of the respective title being selected.
I don't know crud but I think there is a way to debug a little:
e.g. try this:
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
// test if you are here:
echo 'hi, yeah I am here!';
}
or this
echo '<pre>';
var_dump($_POST);
echo '</pre>';
// before:
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
// ...
}
also, take a look at
error_get_last()['message']
I have a page in my clients dashboard for editing his about content.
Once i click on edit button it redirects to another page and there is an option for uploading new image and also content.
Problem :If no new image is uploaded suppose only some text fields are changed and clicked on update the text content changes and redirects to main page but image is deleted from db,but i don't want image to be deleted from the db if no new picture is uploaded.
Two Files Are there
1)index.php
2)editabout.php
index.php
<div class="main-container">
<div class="row">
<div class="container">
<div class="col-lg-12">
<div class="row">
<?php include('db.php'); $select=mysql_query("SELECT * FROM `about`"); while($row=mysql_fetch_array($select)){?>
<div class="col-md-3"><img id="profileimage" src="about/<?php echo $row['image']; ?>" style="width:100%;height:200px;" class="img-thumbnail img-responsive" required>
<div class="row">
<div class="col-md-6"> <input style="width:100%;" class="btn btn-info btn-lg mb-3 mr-3" type="submit" value="Edit"></div>
</div>
</div>
<?php}?>
</div>
</div>
</div>
</div>
editabout.php
<div class="row">
<div class="col-lg-4">
<form action="" method="post" enctype="multipart/form-data">
<div class="main-container file-upload">
<div class="file-upload__dropzone">
<?php
include('db.php');
$select=mysql_query("SELECT * FROM `about` where `sl.no`='$bid' ");
while($row=mysql_fetch_array($select)){
?>
<img id="profileimage" src="about/<?php echo $row['image']; ?>" value="<?php echo $row['image']; ?>" class="img-thumbnail img-responsive" style="width:100%;height:200px;">
<?php } ?>
<div class="file-upload__browse-files">
<button class="btn btn-outline-info btn-lg btn-block btn-rounded file-upload__browse-btn">Browse files</button>
<input id="upload-files-default" name="img" type="file" multiple class="upload" onchange="readURL(this);">
</div><br>
<button class="btn btn-success btn-lg mb-2 mr-3" name="ok" type="submit">Update</button>
</div>
</div>
</form>
</div>
Php code for uploading
include('db.php');
if(isset($_POST['ok']))
{
$photo=$_FILES['img']['name'];
$target_dir = "about/";
$location = $target_dir .$_FILES["img"]["name"];
move_uploaded_file($_FILES['img']['tmp_name'],$location);
$query1="UPDATE `about` SET `image`='$photo',
`up_date`=now()
WHERE `about`.`sl.no` ='$bid'";
mysql_query($query1);
You have to check does the file exist/uploaded or not before executing any query. As an example below:
if(is_uploaded_file($_FILES["img"]["tmp_name"] && file_exists($_FILES["img"]["tmp_name"])){
//update query with picture
//move_uploaded_file here
}else{
//Only query updating does details without move_uploaded_file
}
Above code must be put in the if(isset($_POST["ok"])) code block.
I've uploaded different types of files and I save them in a folder and save into DB the path, all files load them well (.doc, xls ...) except (docx, xlsx ...) . The Docx Files It copies it to the directory but it is not possible to get its name, type size etc.
This is my code:
<?php
require_once 'connect.php';
if($_POST) {
$nombre = $_FILES['archivo']['name'];
$tipo = $_FILES['archivo']['type'];
$tamanio = $_FILES['archivo']['size'];
$ruta = $_FILES['archivo']['tmp_name'];
$destino = "../archivos/" . $nombre;
copy($ruta, $destino);
$sql = "INSERT INTO documentos (tipo,tamano,destino,fecha) VALUES ('$tipo', '$tamanio', '$nombre',NOW())";
$query = $connect->query($sql);
$connect->close();
}
My form:
<form class="form-horizontal" action="../../phpcrud/create_documentos.php" method="POST" id="create_documentos_form" enctype="multipart/form-data">
<div class="modal-body">
<div class="message_create_documentos"></div>
<div class="form-group">
<label for="apemat" class="col-sm-2 control-label">Archivo</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="archivo" name="archivo" placeholder="Archivo">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</form>
So I am trying to insert a php script that gets values for a select element into a modal. But The php script works and gets the right info. But whenever i try and load the script into the modal like so:
<?php include 'script.php' ?>
My modal wont show up. These are my files:
Index.php
<div class="modal fade" id="upload" tabindex="-1">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Tilføj en note</h4>
</div>
<form action="scripts/upload.php" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="name">Navn:</label>
<input type="text" class="form-control" name="name" placeholder="Navn på note..">
</div>
<div class="form-group">
<label for="name">Fag:</label>
<select class="form-control">
<?php include 'scripts/getClasses.php'; ?>
</select>
</div>
<div class="form-group">
<label for="name">Beskrivelse:</label>
<textarea name="description" data-provide="markdown" rows="10"></textarea>
</div>
<label for="file">Vælg fil:</label>
<input type="file" name="file" id="file"><br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Luk</button>
<button type="submit" class="btn btn-success">Upload</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
scripts/getClasses.php
<?php
require 'funcs.php';
$function = new functions;
$class = $function->getClasses();
$numclasses = count($class);
for($i=0;$i<$numclasses;$i++)
{
$id = $class[$i]['id'];
$name = $class[$i]['name'];
echo "<option value='".$id."'>".$name."</option>";
}
?>
snippet of funcs.php
public function getClasses()
//Function that gets all the classes. Used when user adds a new note.
{
require 'connect.php';
$count = 0;
$q = $db->prepare('SELECT * FROM classes ORDER BY name ASC');
$q->execute();
while($row = $q->fetch())
{
$results[$count]['id'] = $row['id'];
$results[$count]['name'] = $row['name'];
$count++;
}
return $results;
}