Create system gallery photos - php

I'm trying to create a system of photos of a product, where the administrator if he wants to add remove or change the position of the photos he does everything by the form.
Form:
<form role="form" id="editProductForm" enctype="multipart/form-data">
<div id="SubPhotos" class="mt-3" style="overflow: auto; white-space: nowrap;">
<hr>
<div class="form-group mt-0 col-md-3">
<label for="uploadPhoto" class="btn btn-primary" role="button" style="cursor:pointer">Add Photo <i class="fas fa-plus"></i></label>
<input type="file" id="uploadPhoto" onchange="readURL(this);" style="display:none;">
</div>
<div class="d-flex">
<label><span id="badgeMainPicture" class='badge badge-primary ml-2'>Main Picture</span></label>
<label class="ml-auto"><span id="badgeTotalPhotos" class='badge badge-secondary'>Amount of Photos: <?php echo count($productImages) ?> de 10</span></label>
</div>
<div id="droppable" style="display: flex;">
<?php $index = 1;
for ($i = 0; $i < count($productImages); $i++) { ?>
<div id="photo<?php echo $index ?>" class="form-group col-lg-3 draggable">
<img id="preview-img" <?php echo isset($productImages[$i]) ? 'src="' . $site . $productImages[$i]['ImagePath'] . '"' : '' ?> height="300px" width="242px" />
<button id="removerPhoto<?php echo $index ?>" class="btn btn-danger btn-removerPhoto shadow-lg" type="button" onclick="removePhoto(<?php echo $index ?>)"><i class="fas fa-times"></i></button>
</div>
<?php
$index++;
} ?>
</div>
</div>
<hr>
<div class="d-flex">
<button type="submit" id="editProduct" class="ml-auto mr-auto btn btn-primary mt-5">Modify Product</button>
</div>
</form>
Contains remove button, draggable to change positions and add photos, everything works fine CLIENT-SIDE
After submit form:
$("#editProductForm").submit(function(e) {
e.preventDefault();
var index = 1;
$(".draggable").each(function() {
var image = $(this).find("#preview-img").attr("src");
var id = $(this).attr("id").substring(4);
if (image.indexOf("https://") > -1) {
$("#photo" + id).attr("id", "photo" + index);
} else {
$("#picture" + id).attr("name", "picture" + index);
}
index++;
});
var formData = new FormData(this);
var index = 1;
$(".draggable").each(function() {
var image = $(this).find("#preview-img").attr("src");
var id = $(this).attr("id").substring(4);
if (image.indexOf("https://") > -1) {
formData.append('picture' + index, image);
} else {
$("#picture" + id).attr("name", "picture" + index);
}
index++;
});
$.post({
url: '<?php echo $site ?>/admin/painel/modifyproduct.php',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
}
});
});
Now comes the question, my code has bug and I don't know how to solve SERVER-SIDE:
function createImage($id, $productCategory)
{
global $db;
$db->query("DELETE FROM pictures WHERE ProductID='$id'");
if (!file_exists("../../../pictures/produtos/$productCategory/MTA$id/")) {
mkdir("../../../pictures/produtos/$productCategory/MTA$id/", 0777, true);
}
$position = 0;
for ($i = 1; $i <= 10; $i++) {
if (isset($_FILES['picture' . $i])) {
$file = $_FILES['picture' . $i]['tmp_name'];
$nameFile = "picture" . $position;
$patchImage = "/pictures/produtos/$productCategory/MTA$id/$nameFile.png";
move_uploaded_file($file, "../../.." . $patchImage);
saveImageInDataBase($id, $patchImage, $position);
$position++;
} else if (isset($_POST['picture' . $i])) {
$file = $_POST['picture' . $i];
$nameFile = "picture" . $position;
$oldName = "../../../" . substr($file, strpos($file, 'pictures/'));
rename($oldName, "../../../pictures/produtos/$productCategory/MTA$id/$nameFile.png");
saveImageInDataBase($id, "/pictures/produtos/$productCategory/MTA$id/$nameFile.png", $position);
$position++;
}
}
}
Bug: There is a bug that when there is already a photo in the folder with the same name (with the position) and another photo being placed with that same position (move_uploaded_file) the old photo will be replaced.
Would there be an easier way to make this photo system work well?

Before doing the move_uploaded_file() you have to check whether the file exists. If so, you'll need to create a new filename. You'll have to do those steps until you find a non-existent file.
while ( TRUE ) { // Loop until we find a non-existent destination filename
$nameFile = "picture" . $position;
$patchImage = "/pictures/produtos/$productCategory/MTA$id/$nameFile.png";
if ( ! file_exists( $patchImage ) ) { // We're good
move_uploaded_file($file, "../../.." . $patchImage);
saveImageInDataBase($id, $patchImage, $position);
break; // Get out of the loop
}
$position++; // Try next position
}

Related

Why won't my delete function respond to the button?

I have a problem my delete function does not work he does not delete the organisation. When I press the button it show the text if I want to delete it I say yes but it only refreshes the site. I am not an advanced programmer and some of the code I did not write myself someone else worked on the project before me so idk why he some codes are written this way and he did not use any framework.
My code
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_FILES['croppedImage'])) logoChange();
// change organisation information is not made yet
if (isset($_POST['update'])) echo "This function is not made yet!";
if (isset($_POST['deleteOrganisation'])) DeleteOrganisations();
}
//this is the logoChange function
function logoChange() {
include '../../../include/db_conn.php';
//get organisation_id
$organisation_id = $_POST['organisation_id'];
//blob file info
$fileName = $_FILES['croppedImage']['name'];
$fileTmpName = $_FILES['croppedImage']['tmp_name'];
$fileSize = $_FILES['croppedImage']['size'];
$fileError = $_FILES['croppedImage']['error'];
//change blob to png
$fileType = 'png';
//check if image is able to upload
if ($fileError === 0) {
//check if file is not too big change number to needs!
if ($fileSize < 1000000) {
//make new random filename
$fileNameNew = uniqid('', true).".".$fileType;
$fileDesination = '../../../img/uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDesination);
//check if organisation already has a logo
$get_organisation_stmt = $conn->prepare('SELECT `organisation_logo` FROM `organisations` WHERE `organisation_id` = ?');
$get_organisation_stmt->bind_param('s', $organisation_id);
$get_organisation_stmt->execute();
$result_organisation = $get_organisation_stmt->get_result();
$row = mysqli_fetch_assoc($result_organisation);
if (is_null($row['organisation_logo'])) {
//if not inserted it
$sqlUpdateLogo = 'UPDATE `organisations` SET `organisation_logo`="'.$fileNameNew.'" WHERE `organisation_id` ="'.$organisation_id.'"';
mysqli_query($conn, $sqlUpdateLogo);
echo 'image inserted';
} else {
//else replace it
unlink('../../../img/uploads/'.$row['organisation_logo']);
$sqlUpdateLogo = 'UPDATE `organisations` SET `organisation_logo`="'.$fileNameNew.'" WHERE `organisation_id` ="'.$organisation_id.'"';
mysqli_query($conn, $sqlUpdateLogo);
echo 'image replaced';
}
}
else {
echo "File to big";
}
} else {
echo "Error in file";
}
}
// here i made the delete function
function DeleteOrganisations() {
include '../../../include/db_conn.php';
//delete the organisation
$getDeleteOrganisation = $_POST['deleteOrganisation'];
$delete_organisation_stmt = $conn->prepare('DELETE FROM `organisations` WHERE `organisation_id`= ?');
$delete_organisation_stmt->bind_param('i', $getDeleteOrganisation);
$delete_organisation_stmt->execute();
$delete_organisation_stmt->close();
}
here are the functions and here is JavaScript
//link for datatable functions
$(document).ready(function(){
$('#organisations').DataTable({
"columnDefs": [
{ "orderable": false, "targets": [0, 5] }
],
"order": [[ 1, "asc" ]]
});
});
//open edit modal for logo
$(document).on("click", ".btnopenEditLogo", function(e) {
event.preventDefault();
var organisationId = $(this).val();
var url = "functions/getOrganisationActions.php";
$.ajax({
type: 'POST',
url : url,
data: {'HiddenLogoid': organisationId},
success: function (data) {
$('#myLogoEditModal').modal('show');
$("#myLogoEditModal .modal-body").html(data);
}
});
});
//open modal with info of user for editing
$(document).on("click", ".btnopenEditOrganisation", function(e) {
event.preventDefault();
var organisationId = $(this).val();
var url = "functions/getOrganisationActions.php";
$.ajax({
type: 'POST',
url : url,
data: {'HiddenOrganisationid': organisationId},
success: function (data) {
$('#myOrganisationEditModal').modal('show');
$("#myOrganisationEditModal .modal-body").html(data);
}
});
});
//delete organisation
$(document).on("click", ".btnRemoveOrganisation", function(e) {
event.preventDefault();
var remove = $(this).val();
var url = "../cms/organisations/functions/postOrganisationActions.php";
Swal.fire({
title: 'Delete this test?',
text: "If you delete the test the questions and all statistics will be lost!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33'
}).then((result) => {
if (result.value) {
$.ajax({
type: 'POST',
url : url,
data: {'deleteOrganisation': remove},
success: function (data) {
Swal.fire({
title: 'Deleted!',
text: "You deleted the survey!",
type: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
}).then((result) => {
if (result.value) {
window.location.reload();
}
});
}
});
} else if (result.dismiss === Swal.DismissReason.cancel) {
Swal.fire (
'Cancelled',
'Your test is safe :)',
'error'
)
}
});
});
this is the index
<?php
session_start();
if (!isset($_SESSION["userId"])) {
header('Location: ../../auth/login');
die();
}
$activePage = "cms";
$activeCMSTab = "organisations";
?>
<!doctype html>
<html lang="en">
<head>
<title>Admin CMS | Organisations</title>
<!-- include header -->
<?php require '../../include/header.php'; ?>
</head>
<body class="d-flex flex-column">
<!-- include navbar -->
<?php require '../../include/navbar.php'; ?>
<!-- include organisation functions -->
<?php require 'functions/getOrganisationsActions.php'; ?>
<div id="main">
<div class="container">
<div class="row">
<div id="sidenav-border" class="col-lg-3 d-none d-md-none d-lg-block">
<?php require '../../include/cms_sidenav.php'; ?>
</div>
<div class="col-lg-9">
<div class="card-theme mt-3">
<div class="clearfix">
<h5 class="card-title-theme float-left"><i class="fas fa-building"></i> Organisation list:</h5>
<i class="fas fa-info-circle fa-fw mt-2 mr-2"></i>
</div>
<hr class="hr-theme" />
<div class="card-body">
<?php getOrganisations(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- footer -->
<?php require '../../include/footer.php'; ?>
<!-- logo modal -->
<?php require 'logo-edit-modal.php'; ?>
<!-- organisation modal -->
<?php require 'organisation-edit-modal.php'; ?>
<!-- logout modal -->
<?php require '../../auth/logout-modal.php'; ?>
<!-- include js scripts -->
<script src="js/organisationFunctions.js"></script>
</body>
</html>
you need get organisation where the button is made the button is at
<?php
function getOrganisations() {
//include DataBase connection
include '../../include/db_conn.php';
//show every organisation that is approved
$sqlCollectAllOrganisations = "SELECT * FROM `organisations` WHERE `approval_admin`='1'";
$resultAllOrganisations = mysqli_query($conn, $sqlCollectAllOrganisations);
echo '<div class="table-responsive">';
echo '<table id="organisations" class="table table-striped table-bordered table-hover">';
echo '<thead>';
echo '<tr>';
echo '<th>Logo</th>';
echo '<th>Organisation</th>';
echo '<th>Parent</th>';
echo '<th>type</th>';
echo '<th>Users</th>';
echo '<th>Tools</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
//Show organisations
if ($resultAllOrganisations->num_rows > 0) {
while ($row = $resultAllOrganisations-> fetch_assoc()) {
echo '<tr>';
//organisation logo
if ($row['organisation_logo'] == '')
echo '<td class="align-middle" align="center"><img src="../../img/stock/no-image-icon.png" class="rounded d-inline mr-1" width="30px"></img><button class="btn btn-link d-inline p-0 btnopenEditLogo" value="'. $row['organisation_id'] .'">edit</button></td>';
else
echo '<td class="align-middle" align="center"><img src="../../img/uploads/'. $row['organisation_logo'] .'" class="rounded border d-inline mr-1" width="30px"><button class="btn btn-link d-inline p-0 btnopenEditLogo" value="'. $row['organisation_id'] .'">edit</button></td>';
//organisation name
echo '<td class="align-middle">' .$row['organisation_name']. '</td>';
//organisation parent
if ($row['organisation_parent'] != null) {
$sqlCollectparent = "SELECT * FROM `organisations` WHERE `organisation_id`='".$row['organisation_parent']."'";
$resultparent = mysqli_query($conn, $sqlCollectparent);
if ($parent = $resultparent-> fetch_assoc()) echo '<td class="align-middle">'.$parent['organisation_name'].'</td>';
} else {
echo '<td class="align-middle"><i class="fas fa-times" style="font-size: 16px;"></i></td>';
}
//organisation type
echo '<td class="align-middle">' . $row['organisation_type'] . '</td>';
//count users
$sqlCountUsers = "SELECT COUNT(organisation_id) AS `count` FROM `users` WHERE `organisation_id`='".$row['organisation_id']."'";
$resultcount = mysqli_query($conn, $sqlCountUsers);
if ($count = $resultcount-> fetch_assoc()) echo '<td class="align-middle">'.$count['count'].'</td>';
//buttons
echo '<td class="align-middle text-center">';
echo '<div class="btn-group">';
echo '<button class="btn-theme btn-theme-success btn-theme-sm mr-1">Add user</button>';
echo '<button class="btn-theme btn-theme-primary btn-theme-sm mr-1 btnopenEditOrganisation" value="'. $row['organisation_id'] .'"><i class="fas fa-edit fa-fw"></i></button>';
if ($_SESSION['organisation_id'] != $row['organisation_id']) echo '<button type="button" class="btn-theme btn-theme-danger btn-theme-sm btnRemoveOrganisation" value=""><i class="fas fa-trash-alt fa-fw"></i></button>';
echo '</div>';
echo '</td>';
echo '</tr>';
}
} else {
//do nothing
}
echo '</tbody>';
echo '</table>';
echo '</div>';
}
?>

Comments show in last post in codeigniter

Check my image all comment show in one post i am pass post_id 53 56 here is 53 comment and 56 comment you see but it show 53 comment in 56 post i have post and comments system like facebook but my problem is that all comments show in last post. please check it my code i have try many method but it's not working if you have any good solution soo please help me
Controller
public function commentlist(){
$conn = mysqli_connect("localhost","root","","finance");
$memberId = 1;
$sql = "SELECT * FROM tbl_comment INNER JOIN signup ON tbl_comment.u_id = signup.id";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
}
public function commentadd(){
$conn = mysqli_connect("localhost","root","","finance");
$u_id = $this->session->userdata('log_in')['id'];
$u_image = $this->session->userdata('log_in')['image'];
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$postID = isset($_POST['tmp']) ? $_POST['tmp'] : "";
$name = array();
$name[0] = $this->session->userdata('log_in')['f_name'];
$name[1] = $this->session->userdata('log_in')['l_name'];
$commentSenderName = implode(" ", $name);
$sql = "INSERT INTO tbl_comment(post_id, parent_comment_id,u_id,u_image,comment,comment_sender_name,date) VALUES ('" . $postID . "','" . $commentId . "','" . $u_id . "','" . $u_image . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
}
this is my view file
View
<form id="frm-comment_<?php echo $id;?>">
<div class="input-row_<?php echo $id;?>">
<?php if($this->session->userdata('log_in')['image'] !=NULL ): ?>
<img src="<?php echo base_url(); ?>uploads/<?php echo $this->session->userdata('log_in')['image'];?>" style="height:42px; width:42px;" class="img-circle">
<?php else : ?><img src="<?php echo base_url('assets/images/generic-avatar.jpg'); ?>" style="height:42px; width:42px;" class="img-circle">
<?php endif; ?>
<input type="hidden" name="comment_id" id="commentId_<?php echo $id; ?>"/>
<input type="hidden" name="tmp" id="tmp" value="<?php echo $id;?>" />
<input class="input-field" type="text" name="comment" id="comment_<?php echo $id; ?>" placeholder="Write a Comment..">
</div>
<input type="button" class="btn-submit" id="submitButton_<?php echo $id;?>" value="Comment" >
<div id="comment-message_<?php echo $id;?>" style='display: none;'>Comments Added Successfully!</div>
<div class="output_<?php echo $id?>" ></div>
</form>
</div>
</div>
</div>
</div>
Script
<script>
$( "#com_<?php echo $id; ?>" ).click(function() {
$("#comment_<?php echo $id;?>").focus();
});
function postReply(commentId) {
$('#commentId_<?php echo $id; ?>').val(commentId);
$("#comment_<?php echo $id; ?>").focus();
}
$(document).ready(function () {
listComment();
});
$("#submitButton_<?php echo $id;?>").click(function () {
$("#comment-message_<?php echo $id;?>").css('display', 'none');
var str = $("#frm-comment_<?php echo $id;?>").serialize();
$.ajax({
url: "<?php echo base_url();?>finance/commentadd",
data: str,
type: 'post',
success: function (response)
{
var result = eval('(' + response + ')');
if (response)
{
$("#comment-message_<?php echo $id;?>").css('display', 'inline-block');
$("#comment_<?php echo $id; ?>").val("");
$("#commentId_<?php echo $id; ?>").val("");
listComment();
} else
{
alert("Failed to add comments !");
return false;
}
}
});
});
function listComment(){
$.post("<?php echo base_url();?>finance/commentlist",
function (data) {
var data = JSON.parse(data);
var comments = "";
var replies = "";
var item = "";
var parent = -1;
var results = new Array();
var list = $("<ul class='outer-comment'>");
var item = $("<li>").html(comments);
for (var i = 0; (i < data.length); i++)
{
var commentId = data[i]['comment_id'];
var post_id = data[i]['post_id'];
parent = data[i]['parent_comment_id'];
if (parent == "0")
{comments = " \ <div class='comment-row'><div class='comment-info'>\ <img src='<?php echo base_url(); ?>uploads/"+data[i]['image']+"' class='img-circle' style='height:47px; width:47px; border:1px solid white;'>\<div class='comment-text'>\ <span>" + data[i]['post_id'] + "</span><span class='posted-by'>" + data[i]['comment_sender_name'] + "</span> " + data[i]['comment'] + "</div>\
</div>\
<div>\
<a class='btn-reply' style='font-size:14px;' onClick='postReply(" + commentId + ")'> Reply</a>\
<span class='posted-at' style='font-size:12px;'>" + data[i]['date'] + "</span>\
</div>\
</div>";
var item = $("<li>").html(comments);
list.append(item);
var reply_list = $('<ul>');
item.append(reply_list);
listReplies(commentId, data, reply_list);
}
}
$(".output_<?php echo $id?>").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
if (commentId == data[i].parent_comment_id)
{
var comments = "\ <div class='comment-row'><div class='comment-info'>\ <img src='<?php echo base_url(); ?>uploads/"+data[i]['image']+"' class='img-circle' style='height:47px; width:47px; border:1px solid white;'>\
<div class='comment-text'> <span class='posted-by'>" + data[i]['comment_sender_name'] + "</span> " + data[i]['comment'] + "</div>\
</div>\
<div>\
\ <span class='posted-at' style='font-size:12px;'>" + data[i]['date'] + "</span>\
</div>\
</div>";
var item = $("<li>").html(comments);
var reply_list = $('<ul>');
list.append(item);
item.append(reply_list);
listReplies(data[i].comment_id, data, reply_list);
}
}
}
</script>
<?php }?>
I think your code is complex because there is not need to save user image ,name in comment table ,you need to use only comment id(auto increment) post id, user id , comment.
Yo get all comments for particular post you should fetch by post ir for that post.
Example :- when user click on particular post , suppose its post id is 1 then as click click on this you have to pass a request with this post id to comment table where query will match this post id in comment id if this condition true then redirect page to view with all comment and show them.
Controller
Query:- $this->model_name->function_name($id);
In model
$this->db->where('post_id', $id);
$this->db->get('comment_table')->result_array();
This query will fetch all comment for clicked post.

Joomla uploading images issue

I installed BT Property component for my Joomla site and when I select multiple of images (more than 3 or 4) which I want to upload for my article, it nothing happens. The images won't upload. I try to change the code but I don't know what the problem is.
This is the code I want to change.
<?php
defined('_JEXEC') or die('Restricted access');
$document = JFactory::getDocument();
$path = $this->params->get('images_path', 'images/bt_property');
?>
<ul class="adminformlist" id="uploading">
<li><input type="file" name="attachment" id="attachment" multiple /><img id="spinner"
style="display: none; margin-left: 10px;"
src="<?php echo JURI::root(); ?>components/com_bt_property/assets/img/spinner.gif">
<div style="clear: both"></div>
<div id="btss-message"></div></li>
</ul>
<script type="text/javascript">
(function($){
var files = [];
$("#attachment").change(function(event) {
$.each(event.target.files, function(index, file) {
var reader = new FileReader();
reader.onload = function(event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
files.push(object);
if(files.length==1){
uploadFile(index);
$('#spinner').show();
$("#btss-message").show();
}
};
reader.readAsDataURL(file);
});
});
function uploadFile(index){
$.ajax({url: "index.php?option=com_bt_property&task=properties.upload",
type: 'POST',
data: {filename: files[index].filename, filedata: files[index].data},
success: function(response, status, xhr){
uploadHandler(response, status, xhr);
if(index == files.length-1){
$('#spinner').hide();
files = [];
$("#attachment").val('');
$("#btss-message").delay(1000).slideUp(function(){
$("#btss-message").html('');
});
}else{
index++;
uploadFile(index);
}
}
});
}
function uploadHandler(response, status, xhr) {
var data = jQuery.parseJSON(response);
if(data == null){
showMessage("<br /><span style=\"color: red;\">Loading Failed</span>");
}else{
var file = data.files;
if (!data.success) {
showMessage("<br /><span style=\"color: red;\"> " + data.message +"</span>");
}
else {
var html = '<li>';
html += '<input class="input-default" title="Make default" name="default_image" type="radio" value="'+file.filename+'" />';
html += '<img class="img-thumb" src="<?php echo JURI::root() . $path . '/tmp/' . ($this->params->get('thumbimgprocess', 1) == -1 ? 'original' : 'thumb') . '-'; ?>'+file.filename+'" />';
html += '<input type="hidden" name="image_id[]" value="0" />';
html += '<input type="hidden" name="image_filename[]" value="'+file.filename+'" /><br/>';
html +='Edit';
html +='<a href="javascript:void(0)" class="remove" onclick="removeImage(this)" >Remove</a>';
html += '</li>';
jQuery('#sortable').append(html);
jQuery('#sortable li:last-child ').find('a.edit').data('title', file.title);
reNewItem();
showMessage('<br />' + file.title + " uploaded successfully!");
}
}
}
function showMessage(msg){
$("#btss-message").append(msg);
}
})(jQuery);
</script>
Is there a way to fix the code? I would be very thankful for any answer.
Your file object is coming up as undefined, and thus you're not able to use file.filename.
Your problem is most likely with this line var file = data.files; - are you sure about data.files?

Load the Images using jquery File Api

We are using jquery.fileApi.js to upload images in a form alongwith Yii Framework. https://rubaxa.github.io/jquery.fileapi/
We have successfully uploaded the images on the server.
Here's the code to upload a file,
<script>
var examples = [];
var imageNames = [];
</script>
<div id="multiupload">
<form class="b-upload b-upload_multi" action="<?php echo $this->createUrl('item/sellNow') ?>" method="POST" enctype="multipart/form-data">
<div class="whiteBox clearfix" id="mulUplImgParent" style="display: none;">
<ul id="sortable" class="js-files b-upload__files">
<li class="col-xs-6 col-sm-2 col-md-2 js-file-tpl b-thumb" data-id="<%=uid%>" title="<%-name%>, <%-sizeText%>">
<header class="clearfix">
<div data-fileapi="file.remove" class="b-thumb__del pull-left"></div>
<% if( /^image/.test(type) ){ %>
<div data-fileapi="file.rotate.cw" class="b-thumb__rotate pull-right"></div>
<% } %>
</header>
<div class="b-thumb__preview">
<div class="b-thumb__preview__pic"></div>
</div>
</li>
</ul>
</div>
<div class="form-group">
<div id="uploadMulImgBtn" class="btn btn-pink btn-small js-fileapi-wrapper">
<span>Browse Images</span>
<input type="file" name="filedata" />
</div>
<figure class="note"><strong>Hint:</strong> You can upload all images at once!</figure>
</div>
</form>
<script type="text/javascript">
examples.push(function() {
$('#multiupload').fileapi({
multiple: true,
url: '<?php echo $this->createUrl('item/uploadImage') ?>',
paramName: 'filedata',
duplicate: false,
autoUpload: true,
onFileUpload: function(event, data) {
imageNames.push(data.file.name);
$("#item-images").val(imageNames.join(','));
},
onFileRemoveCompleted: function(event, data) {
var removeItem = data.name;
imageNames = jQuery.grep(imageNames, function(value) {
return value != removeItem;
});
$("#item-images").val(imageNames.join(','));
},
elements: {
ctrl: {upload: '.js-upload'},
empty: {show: '.b-upload__hint'},
emptyQueue: {hide: '.js-upload'},
list: '.js-files',
file: {
tpl: '.js-file-tpl',
preview: {
el: '.b-thumb__preview',
width: 80,
height: 80
},
upload: {show: '.progress', hide: '.b-thumb__rotate'},
complete: {hide: '.progress'},
progress: '.progress .bar'
}
}
});
});
</script>
</div>
Server Side Code
public function actionUploadImage(){
$userId = Yii::app()->user->id;
$tmpFilePath = $_FILES['filedata']['tmp_name'];
$imageName = $_FILES['filedata']['name'];
$path = 'user_files/';
if(is_dir($path))
{
$dir = $path.$userId;
if(!is_dir($dir))
{
mkdir($dir,0777);
}
$subDir = $dir . '/temp';
if(!is_dir($subDir))
{
mkdir($subDir,0777);
}
$imagePath = "$subDir/$imageName";
move_uploaded_file($tmpFilePath, "$subDir/$imageName");
$image = new Image($imagePath);
$image->resize(190, 190);
$image->save();
$jsonResponse = array('imageName' => $imageName,'imagePath' => $imagePath);
echo CJSON::encode($jsonResponse);
}
//var_dump($_FILES);
//var_dump($_POST);die;
}
We are having issues how to load those images again on the form.
We want to show uploaded images on edit form along with all the event handlers bind through jquery.fileApi .
We cant figure out a way which could render already uploaded images.
Thanks,
Faisal Nasir

Random picture form database and rating system

Hey i have a problem on my website i want to display a image with a rating under and then when i rate the image it should change to the next picture. And there is my problem because it displays the next picture correctly but it doesn't change the id in the rating system so i am rating the same picture again and again
Source code:
$place="upload/";
$first = mysql_query("SELECT * FROM images ORDER BY RAND()");
while($wor = mysql_fetch_array($first))
{
$id=$wor['id'];
$name = $wor['name'];
$image = $place . $wor['name'];
}
$number="1";
$wrongnumber="2";
$random = mysql_query("SELECT * FROM images ORDER BY RAND()");
$place="upload/";
echo '<script> ';
while($wor = mysql_fetch_array($random))
{
$ids=$wor['id'];
$name = $wor['name'];
$images = $place . $wor['name'];
$number=$number + 1;
$wrongnumber=$wrongnumber + 1;
echo 'function ' . 'changeSrc' . $number . '() '; ?>
{
document.getElementById("rand").src="<? echo $images;?>";
document.getElementById("button").onclick=changeSrc<? echo $wrongnumber;?>;
document.getElementById("102").id=<? echo $ids;?>;
}
<?
}
?>
</script>
<img id="rand" src="<? echo $image;?>"><br>
<div id="button" onclick="changeSrc2()">
<div class="rate_widget" id="102">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
</div>
The output code:
// This is the first thing we add ------------------------------------------
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'ratings.php',
out_data,
function(INFO) {
$(widget).data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
// can't use 'this' because it wont contain the updated data
set_votes($(this).parent());
}
);
// This actually records the vote
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
$.post(
'setcookie.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
// END FIRST THING
</script><script> function changeSrc2() {
document.getElementById("rand").src="upload/1329614519daily_erotic_picdump_48-2-500x334.jpg";
document.getElementById("button").onclick=changeSrc3;
document.getElementsByClassName('rate_widget').id="125";
}
function changeSrc3() {
document.getElementById("rand").src="upload/1329614453tumblr_leb4pwc0Xc1qzy9ouo1_1280-1024x640.jpg";
document.getElementById("button").onclick=changeSrc4;
document.getElementsByClassName('rate_widget').id="65";
}
function changeSrc4() {
document.getElementById("rand").src="upload/1329614295daily_erotic_picdump_20-copy-500x333.jpg";
document.getElementById("button").onclick=changeSrc5;
document.getElementsByClassName('rate_widget').id="44";
}
function changeSrc5() {
document.getElementById("rand").src="upload/1329614301daily_erotic_picdump_80-2-500x375.jpg";
document.getElementById("button").onclick=changeSrc6;
document.getElementsByClassName('rate_widget').id="51";
}
function changeSrc6() {
document.getElementById("rand").src="upload/13296142941-3-450x600.jpg";
document.getElementById("button").onclick=changeSrc7;
document.getElementsByClassName('rate_widget').id="225";
}
function changeSrc7() {
document.getElementById("rand").src="upload/1329614284tumblr_l53l0qM6HB1qc4zlyo1_500-450x568.jpg";
document.getElementById("button").onclick=changeSrc8;
document.getElementsByClassName('rate_widget').id="19";
}
function changeSrc8() {
document.getElementById("rand").src="upload/1329614454tumblr_lro15r2fkh1qzlro6o1_500-450x301.jpg";
document.getElementById("button").onclick=changeSrc9;
document.getElementsByClassName('rate_widget').id="73";
}
function changeSrc9() {
document.getElementById("rand").src="upload/tumblr_mccaolmQPE1regfy1o1_500.jpg";
document.getElementById("button").onclick=changeSrc10;
document.getElementsByClassName('rate_widget').id="272";
}
function changeSrc10() {
document.getElementById("rand").src="upload/1329614297Pix-Mix-304-img012-500x312.jpg";
document.getElementById("button").onclick=changeSrc11;
document.getElementsByClassName('rate_widget').id="47";
}
</script>
<img id="rand" src="upload/1329614465tumblr_lscy8aqOFE1qg7sdjo1_500-450x322.jpg"><br>
<div id="button" onclick="changeSrc2()">
<div class="rate_widget" id="99">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
</div>
document.getElementById("button").onclick=changeSrc<? echo $wrongnumber;?>;
Aren't you missing brackets?
document.getElementById("button").onclick=changeSrc<? echo $wrongnumber;?>();
By the way, to reduce data laod add LIMIT 1 to your SQL query when retrieving only one row.

Categories