Display most liked post on a page php - javascript

I written a script where users can post without signing up or logging in and recieve likes. Sumbitted posts are being displayed on a page and post with most likes is first, which is great, but I created a Most Liked section where I would like to display post with most likes.
comment-like-unlike.php
?php
require_once ("db.php");
$memberId = 1;
$commentId = $_POST['comment_id'];
$likeOrUnlike = 0;
if($_POST['like_unlike'] == 1)
{
$likeOrUnlike = $_POST['like_unlike'];
}
$sql = "SELECT * FROM tbl_like_unlike WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if (! empty($row))
{
$query = "UPDATE tbl_like_unlike SET like_unlike = " . $likeOrUnlike . " WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
} else
{
$query = "INSERT INTO tbl_like_unlike(member_id,comment_id,like_unlike) VALUES ('" . $memberId . "','" . $commentId . "','" . $likeOrUnlike . "')";
}
mysqli_query($conn, $query);
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
$totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>
comment-add.php
<?php
require_once ("db.php");
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$commentSenderName = isset($_POST['name']) ? $_POST['name'] : "";
$date = date('Y-m-d H:i:s');
$sql = "INSERT INTO tbl_comment(parent_comment_id,comment,comment_sender_name,date) VALUES ('" . $commentId . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
?>
get-like-unlike.php
<?php
require_once ("db.php");
$commentId = $_POST['comment_id'];
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
$totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>
comment-list.php
<?php
require_once ("db.php");
$memberId = 1;
$sql = "SELECT tbl_comment.*,tbl_like_unlike.like_unlike FROM tbl_comment LEFT JOIN tbl_like_unlike ON tbl_comment.comment_id = tbl_like_unlike.comment_id AND member_id = " . $memberId . " ORDER BY tbl_like_unlike.like_unlike DESC, tbl_like_unlike.date DESC";
$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);
?>
index.php:
<div class="comment-form-container">
<form id="frm-comment">
<div class="input-row">
<input type="hidden" name="comment_id" id="commentId"
placeholder="Name" /> <input class="input-field"
type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="input-row">
<textarea class="input-field" type="text" name="comment"
id="comment" placeholder="Add a Comment"> </textarea>
</div>
<div>
<font color="white"><input type="button" class="btn-submit" id="submitButton"
value="Publish" /></font>
</div>
</form>
</div>
<div id="output"></div>
<script>
var totalLikes = 0;
var totalUnlikes = 0;
function postReply(commentId) {
$('#commentId').val(commentId);
$("#name").focus();
}
$("#submitButton").click(function () {
$("#comment-message").css('display', 'none');
var str = $("#frm-comment").serialize();
$.ajax({
url: "comment-add.php",
data: str,
type: 'post',
success: function (response)
{
var result = eval('(' + response + ')');
if (response)
{
$("#comment-message").css('display', 'inline-block');
$("#name").val("");
$("#comment").val("");
$("#commentId").val("");
listComment();
} else
{
alert("Failed to add comments !");
return false;
}
}
});
});
$(document).ready(function () {
listComment();
});
function listComment() {
$.post("comment-list.php",
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'];
parent = data[i]['parent_comment_id'];
var obj = getLikesUnlikes(commentId);
if (parent == "0")
{
if(data[i]['like_unlike'] >= 1)
{
like_icon = "<img src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
else
{
like_icon = "<img style='display:none;' src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
comments = "\
<div class='comment-row'>\
<div class='comment-info'>\
<span class='commet-row-label'>from</span>\
<span class='posted-by'>" + data[i]['comment_sender_name'] + "</span>\
<span class='commet-row-label'>at</span> \
<span class='posted-at'>" + data[i]['date'] + "</span>\
</div>\
<div class='comment-text'>" + data[i]['comment'] + "</div>\
<div>\
<a class='btn-reply' onClick='postReply(" + commentId + ")'>Reply</a>\
</div>\
<div class='post-action'>\ " + like_icon + " \
<span id='likes_" + commentId + "'> " + totalLikes + " likes </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").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
var obj = getLikesUnlikes(data[i].comment_id);
if (commentId == data[i].parent_comment_id)
{
if(data[i]['like_unlike'] >= 1)
{
like_icon = "<img src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
else
{
like_icon = "<img style='display:none;' src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
var comments = "\
<div class='comment-row'>\
<div class='comment-info'>\
<span class='commet-row-label'>from</span>\
<span class='posted-by'>" + data[i]['comment_sender_name'] + "</span>\
<span class='commet-row-label'>at</span> \
<span class='posted-at'>" + data[i]['date'] + "</span>\
</div>\
<div class='comment-text'>" + data[i]['comment'] + "</div>\
<div>\
<a class='btn-reply' onClick='postReply(" + data[i]['comment_id'] + ")'>Reply</a>\
</div>\
<div class='post-action'> " + like_icon + " \
<span id='likes_" + data[i]['comment_id'] + "'> " + totalLikes + " likes </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);
}
}
}
function getLikesUnlikes(commentId)
{
$.ajax({
type: 'POST',
async: false,
url: 'get-like-unlike.php',
data: {comment_id: commentId},
success: function (data)
{
totalLikes = data;
}
});
}
function likeOrDislike(comment_id,like_unlike)
{
$.ajax({
url: 'comment-like-unlike.php',
async: false,
type: 'post',
data: {comment_id:comment_id,like_unlike:like_unlike},
dataType: 'json',
success: function (data) {
$("#likes_"+comment_id).text(data + " likes");
if (like_unlike == 1) {
$("#like_" + comment_id).css("display", "none");
$("#unlike_" + comment_id).show();
}
if (like_unlike == -1) {
$("#unlike_" + comment_id).css("display", "none");
$("#like_" + comment_id).show();
}
},
error: function (data) {
alert("error : " + JSON.stringify(data));
}
});
}
</script>
I will post picture of a website just you guys have a clue what Im talking about:
This is where I want most liked post:

SELECT posts from your_table ORDER BY likes DESC

Related

onchange function calling infinity times

Here i am creating table rows with two dropdowns
`
counter = 0;// Global Variable
function addNewRow(){
counter++;
$('#purchase_order').append('<tr id='+counter+'>' +
'<td>' +
'<select name="code'+counter+'" onchange="return getItemNamesByTypeID('+counter+')" class="form-control" id="code'+counter+'">' +
'<option value="0">--Item Code --</option>' +
'<?php
$query = "SELECT * FROM product_packing_relation WHERE sub_cat_id !=0000";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["id"] .'">' . "PT_".$row['product_type_id']."_".$row['id'] .'</option>';
}
?>' +
'</select>' +
'</td>' +
'<td>' +
'<select name="product'+counter+'" onchange="return getItemNamesByTypeID('+counter+')" class="form-control" id=product'+ counter +'>' +
'<option value="0">--Item Code --</option>' +
'<?php
$query = "SELECT * FROM vw_product_packing_relation";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["id"] .'">' . $row['product_name'].'_'.$row['item_size'].$row['item_unit'].'_'.$row['bundle_type'].'_'.$row['pack_size'] .'</option>';
}
?>' +
'</select>' +
'</td>' +
'<td><input class="form-control" type="test" name=uom'+ counter +' id=uom'+ counter +' /></td>' +
'</tr>');
$("#code"+counter).select2();
$("#product"+counter).select2();
}`
Now i try to do that if user change any dropdown the selected key change the other dropdown here is the code.
`function getItemNamesByTypeID(counter){
event.preventDefault();
var product_packing_id=0;
product_packing_id = $("#code" + counter + " option:selected").val();
if(product_packing_id == 0)
{
product_packing_id = $("#product" + counter + " option:selected").val();
}
alert(product_packing_id);
debugger;
$("#code"+counter).val(product_packing_id);
$("#code"+counter).change();
$("#product" + counter).val(product_packing_id);
$("#product" + counter).change();
return false;
}`
Now the problem is if i change any dropdown it starts calling onchange function infinite times.

Select2 Not active

<script>
$(document).ready(function(){
$("#btn-tambah-form").click(function(){
var jumlah = parseInt($("#jumlah-form").val());
var nextform = jumlah + 1;
$("#insert-form").append(
"<div class='row mb-10 p-10'>" +
" <div class='input-group col-md-2'>" +
" <?php $result = mysqli_query($conn, 'SELECT * FROM produk');?>" +
" <?php $jsArray = 'var idproduk = new Array();\n';?>" +
" <select class='form-control select2' id=\'idproduk"+nextform+"\' name=\'idproduk[]\' onchange=\'changeProduk"+nextform+"(this.value),sum();\' required>" +
" <option></option>" +
" <?php while ($row = mysqli_fetch_array($result)) {?>" +
" <?php echo '<option value=\'' . $row['idproduk'] . '\'>' . $row['produk_nama'] . '</option>';?>" +
" <?php$jsArray .= 'idproduk[\'' . $row['idproduk'] . '\'] = {harga_beli:\'' . addslashes($row['harga_beli']) . '\',produk_satuan:\'' . addslashes($row['produk_satuan']) . '\'};\n';?>" +
" <?php }?>" +
" </select>" +
" </div>" +
"</div>");
$("#jumlah-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#jumlah-form").val("1");
});
});
</script>
can someone help me. why my select2 not active when i put them on javascript.
when i put them outside java they can run correct.
please help me how to solve this code.
There is problem with backslashed quotes, remove them. It should be all.
<select class='form-control select2' id='idproduk"+nextform+"' name='idproduk[]' onchange='changeProduk"+nextform+"(this.value),sum();' required>" +

Count like and unlike php

I written a simple script where users can post without sign up or log in, something like conffesion website, people can post and get like and unlike on their posts. I want to count like then sort by most popular and most newest and show it on a main page, and I tried literally everything but nothing seems to work, heres my code:
comment-like-unlike.php
?php
require_once ("db.php");
$memberId = 1;
$commentId = $_POST['comment_id'];
$likeOrUnlike = 0;
if($_POST['like_unlike'] == 1)
{
$likeOrUnlike = $_POST['like_unlike'];
}
$sql = "SELECT * FROM tbl_like_unlike WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if (! empty($row))
{
$query = "UPDATE tbl_like_unlike SET like_unlike = " . $likeOrUnlike . " WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
} else
{
$query = "INSERT INTO tbl_like_unlike(member_id,comment_id,like_unlike) VALUES ('" . $memberId . "','" . $commentId . "','" . $likeOrUnlike . "')";
}
mysqli_query($conn, $query);
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
$totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>
comment-add.php
<?php
require_once ("db.php");
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$commentSenderName = isset($_POST['name']) ? $_POST['name'] : "";
$date = date('Y-m-d H:i:s');
$sql = "INSERT INTO tbl_comment(parent_comment_id,comment,comment_sender_name,date) VALUES ('" . $commentId . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
?>
get-like-unlike.php
<?php
require_once ("db.php");
$commentId = $_POST['comment_id'];
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
$totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>
And my index.php code for posts and likes:
<div class="comment-form-container">
<form id="frm-comment">
<div class="input-row">
<input type="hidden" name="comment_id" id="commentId"
placeholder="Name" /> <input class="input-field"
type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="input-row">
<textarea class="input-field" type="text" name="comment"
id="comment" placeholder="Add a Comment"> </textarea>
</div>
<div>
<font color="white"><input type="button" class="btn-submit" id="submitButton"
value="Publish" /></font>
</div>
</form>
</div>
<div id="output"></div>
<script>
var totalLikes = 0;
var totalUnlikes = 0;
function postReply(commentId) {
$('#commentId').val(commentId);
$("#name").focus();
}
$("#submitButton").click(function () {
$("#comment-message").css('display', 'none');
var str = $("#frm-comment").serialize();
$.ajax({
url: "comment-add.php",
data: str,
type: 'post',
success: function (response)
{
var result = eval('(' + response + ')');
if (response)
{
$("#comment-message").css('display', 'inline-block');
$("#name").val("");
$("#comment").val("");
$("#commentId").val("");
listComment();
} else
{
alert("Failed to add comments !");
return false;
}
}
});
});
$(document).ready(function () {
listComment();
});
function listComment() {
$.post("comment-list.php",
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'];
parent = data[i]['parent_comment_id'];
var obj = getLikesUnlikes(commentId);
if (parent == "0")
{
if(data[i]['like_unlike'] >= 1)
{
like_icon = "<img src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
else
{
like_icon = "<img style='display:none;' src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
comments = "\
<div class='comment-row'>\
<div class='comment-info'>\
<span class='commet-row-label'>from</span>\
<span class='posted-by'>" + data[i]['comment_sender_name'] + "</span>\
<span class='commet-row-label'>at</span> \
<span class='posted-at'>" + data[i]['date'] + "</span>\
</div>\
<div class='comment-text'>" + data[i]['comment'] + "</div>\
<div>\
<a class='btn-reply' onClick='postReply(" + commentId + ")'>Reply</a>\
</div>\
<div class='post-action'>\ " + like_icon + " \
<span id='likes_" + commentId + "'> " + totalLikes + " likes </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").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
var obj = getLikesUnlikes(data[i].comment_id);
if (commentId == data[i].parent_comment_id)
{
if(data[i]['like_unlike'] >= 1)
{
like_icon = "<img src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
else
{
like_icon = "<img style='display:none;' src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
var comments = "\
<div class='comment-row'>\
<div class='comment-info'>\
<span class='commet-row-label'>from</span>\
<span class='posted-by'>" + data[i]['comment_sender_name'] + "</span>\
<span class='commet-row-label'>at</span> \
<span class='posted-at'>" + data[i]['date'] + "</span>\
</div>\
<div class='comment-text'>" + data[i]['comment'] + "</div>\
<div>\
<a class='btn-reply' onClick='postReply(" + data[i]['comment_id'] + ")'>Reply</a>\
</div>\
<div class='post-action'> " + like_icon + " \
<span id='likes_" + data[i]['comment_id'] + "'> " + totalLikes + " likes </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);
}
}
}
function getLikesUnlikes(commentId)
{
$.ajax({
type: 'POST',
async: false,
url: 'get-like-unlike.php',
data: {comment_id: commentId},
success: function (data)
{
totalLikes = data;
}
});
}
function likeOrDislike(comment_id,like_unlike)
{
$.ajax({
url: 'comment-like-unlike.php',
async: false,
type: 'post',
data: {comment_id:comment_id,like_unlike:like_unlike},
dataType: 'json',
success: function (data) {
$("#likes_"+comment_id).text(data + " likes");
if (like_unlike == 1) {
$("#like_" + comment_id).css("display", "none");
$("#unlike_" + comment_id).show();
}
if (like_unlike == -1) {
$("#unlike_" + comment_id).css("display", "none");
$("#like_" + comment_id).show();
}
},
error: function (data) {
alert("error : " + JSON.stringify(data));
}
});
}
</script>
comment-list.php
<?php
require_once ("db.php");
$memberId = 1;
$sql = "SELECT tbl_comment.*,tbl_like_unlike.like_unlike FROM tbl_comment LEFT JOIN tbl_like_unlike ON tbl_comment.comment_id = tbl_like_unlike.comment_id AND member_id = " . $memberId . " ORDER BY parent_comment_id asc, comment_id asc";
$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);
?>
Im really looking forward for some help, ive been working on this script for a while and this is the last thing I need before launching, thanks in advice!
Here's a picture of a website, just to see how its working
You should write your query in comment-list.php like this
$sql = "SELECT tbl_comment.*,tbl_like_unlike.like_unlike FROM tbl_comment LEFT JOIN tbl_like_unlike ON tbl_comment.comment_id = tbl_like_unlike.comment_id AND member_id = " . $memberId . " ORDER BY tbl_like_unlike.like_unlike DESC, tbl_comment.date DESC";
This will automatically sort your data to have comment with most likes on top and then sort by the newest date. So if a comment has the same amount of likes of another comment, the newest will show up on top.
COMMENT RESPONSE
You can do it in javascript like this:
for (var i = 0; i < data.length; i++) {
if(i == 0) {
//put comment at top of page
} else {
// Put comment in normal place
}
}

dynamic form fields with javascript an php: It doesn't work

I have a small javascript which add form-fields dynamically.
My javascript snippet without any php codes works fine.
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />' );
});
});
</script>
But in this script i need an array that read entries from a database for a select option field (dropdown).
I do it like this:
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field1_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />'
+ '<select name="dynfields3[]' + '">
<?php
$abfrage = "SELECT * FROM artikel";
mysql_query("SET NAMES SET 'utf8'");
$ergebnis = mysql_query($abfrage);
while($row = mysql_fetch_object($ergebnis))
{
$id = $row->id;
$name = $row->name;
$beschreibung = $row->beschreibung;
$preis = $row->preis;
echo " <option value='$row->id'>$row->name;</option> ";
}
?>
</select><br />'
);
});
});
</script>
It doesn't work. I get the following error
Uncaught SyntaxError: Unexpected token ILLEGAL
What's wrong? Iam very glad for any help.
Regards,
Stefan
You can try this :
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field1_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />'
+ '<select name="dynfields3[]">' +
+ '<?php $abfrage = "SELECT * FROM artikel"; mysql_query("SET NAMES SET 'utf8'"); $ergebnis = mysql_query($abfrage); while($row = mysql_fetch_object($ergebnis)){?>'
+ '<option value="' + '<?php echo $row->id ?>' + '">' + '<?php echo $row->name ?>' + '</option>'
+ '<?php }?></select></br>'
);
});
});
</script>
I think the error is here
+ '<select name="dynfields3[]' + '">
maybe you intend
+ '<select name="dynfields3[]" >' +
<?php
$abfrage = "SELECT * FROM artikel";
mysql_query("SET NAMES SET 'utf8'");
$ergebnis = mysql_query($abfrage);
while($row = mysql_fetch_object($ergebnis))
{
$id = $row->id;
$name = $row->name;
$beschreibung = $row->beschreibung;
$preis = $row->preis;
echo " <option value='$row->id'>$row->name;</option> ";
}
?>
+ '</select><br />';

Counting outputted results and send to database

I am wanting output of data from my database to display in a numbered list. Say I have four names in the database. John, suzy, Tom, Linda. I then do a shuffle mix of those names and display them. They appear on my page like this...
undefined John
undefined Suzy
undefined Tom
undefined Linda
I want them to appear as
1 John
2 Suzy
3 Tom
4 Linda
I then want those numbers to send to my database in the order they were in and affiliated with the name they were next to. Right now when they send to my database, each record shows 4, so it is only counting the outputted rows.
I modified my existing script to enable my page to count as a list. However, the count output is not displaying on the page. It shows as undefined, but it is sending as the number 4 to my database.
Why is this not working?
I modified this JS
//'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
To
'<div class="shuffle_results">' + data[i].drafted_order + ' '+ data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
Full Code
$count = 0;
foreach ($array as $result) :
$count++;
$shuffle_count = $count;
$shuffle_firstname = htmlentities($result['firstname']);
$shuffle_lastname = htmlentities($result['lastname']);
$shuffle_id = htmlentities($result['id']);
$shuffle_username = htmlentities($result['username']);
$shuffle_email = htmlentities($result['email']);
?>
<input type="hidden" name="count[]" value="<?php echo $shuffle_count; ?>">
<input type="hidden" name="firstname[]" value="<?php echo $shuffle_firstname; ?>">
<input type="hidden" name="lastname[]" value="<?php echo $shuffle_lastname; ?>">
<input type="hidden" name="id[]" value="<?php echo $shuffle_id; ?>">
<input type="hidden" name="username[]" value="<?php echo $shuffle_username; ?>">
<input type="hidden" name="email[]" value="<?php echo $shuffle_email; ?>">
<?php
endforeach;
// only show this button if we have done a shuffle
if ( isset($_POST['shuffle'] ) ) :
echo '<input type="submit" value="Finalize Draft Order" name="insert">';
endif;
?>
</form>
<?php
if (isset($_POST['insert'])) {
$con = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$draft_stmt2 = $con->prepare("INSERT INTO drafted_players (user_id, drafted_order, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?, ?)");
if ( false===$draft_stmt1|| false===$draft_stmt2 ) {
// Check Errors for prepare
die('Add to user players prepare() failed: ' . htmlspecialchars($con->error));
}
$draft_stmt2->bind_param('iissss', $shuffle_id, $shuffle_count, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);
foreach ($_POST['id'] as $i => $shuffle_id) {
$shuffle_firstname = $_POST['firstname'][$i];
$shuffle_lastname = $_POST['lastname'][$i];
$shuffle_username = $_POST['username'][$i];
$shuffle_email = $_POST['email'][$i];
$draft_stmt2->execute() or
die('Add to user players execute() failed: ' . htmlspecialchars($draft_stmt2->error));
}
JS
var interval = setInterval(function(){
if( i <= data.length){
console.log( data[i] );
$('#results').append('<div class="result">' +
//'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<div class="shuffle_results">' + data[i].drafted_order + ' '+ data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
var $this = $('.shuffle_results:last');
$this.show().animate({
'left': 0 + 'px',
'bottom': + '0px'
//$(document).height() - (lineheight * data.length)
}, {
duration: time
});
i++;
} else {
clearInterval(interval);
}
}, 3000);
};
$(function(){
$('form[name="form"]').on('submit', function(e){
e.preventDefault();
$.post('shuffle_results.php', function(data){
var o = $.parseJSON(data);
displayResults(o);
});
});
});
//End test shuffle
$(document).ready(function () {

Categories

Resources