I have one page (resto presentation), and one blue img (like icon).
When I click like_icon, if the user never vote for this resto, I want:
- to increase the vote (saving into mysql database as integer);
- show the new value in the page (without refresh page);
- change the like icon (red icon, always clickable);
If the user already voted, on click icon:
- descrease the vote (update the resto table);
- show the new value in the page (without refresh page);
- change the like icon to blue img (always clickable).
This is what I have tried, but not works properly. What is wrong? And how can I do this?
Thank you.
HTML:
...
...
<?php include 'test.php'; ?>
<div id="idlike"><?php echo $idlike[0]; ?></div>
<label for="like">
<img id="likeimg" src="/img/like.png" style="cursor: pointer;" />
<script>
var x = document.getElementById("idlike").value;
if (x > 0) {
$("#likeimg").attr('src', '/img/dislike.png');
//document.getElementById("likeimg").innerHTML = <img scr="/img/dislike.png">;
}
else {
$("#likeimg").attr('src', '/img/like.png');
//document.getElementById("likeimg").innerHTML = <img scr="/img/like.png">;
}
</script>
</label>
<div id="likeimg"></div>
<form method="POST" action="resto-test.php?id=1">
<input type="submit" id="vote" name="vote" value="" style="display: none;" />
</form>
<script>
$("#likeimg").click(function(){
$("#vote").click();
});
</script>
...
...
test.php:
<?php
//date_default_timezone_set("Europe/Bucharest");
require('login/dbconfig.php');
session_start();
$login_session = $_SESSION['login_user'];
$idresto = 1;
$query = "SELECT id FROM users WHERE username = '$login_session'";
$result = mysqli_query($dbconfig, $query);
$iduser = mysqli_fetch_array($result);
//$query = "SELECT id FROM likes WHERE id_user = (SELECT id FROM users WHERE username = '$login_session')";
$query = "SELECT id FROM likes WHERE id_user = $iduser[0]";
$result = mysqli_query($dbconfig, $query);
$idlike = mysqli_fetch_array($result);
//echo "<div id='idlike'>";
//if ($idlike[0]) {
//echo $idlike[0];
//}
//else {
//echo "0";
//}
//echo "</div>";
$query = "SELECT COUNT(id_resto) FROM likes WHERE id_resto = $idresto";
$result = mysqli_query($dbconfig, $query);
$nrl = mysqli_fetch_array($result);
if (isset($_POST['vote'])) {
if (!$idlike[0]) {
//echo "<div id='likes'><img id='likeimg' src='/img/like.png'>";
//echo "<div id='likes'><img id='likeimg' src='/img/like.png'>";
$query = "INSERT INTO likes (id, id_user, id_resto, id_fel, id_gr) VALUES (default, $iduser[0], $idresto, 0, 0)";
$result = mysqli_query($dbconfig, $query);
$query = "UPDATE restos SET likes = ($nrl[0]+1) WHERE id = $idresto";
$result = mysqli_query($dbconfig, $query);
//echo "<span id='likenr'> " . ($nrl[0] + 1). "</span></div>";
echo "<span id='likenr'> " . ($nrl[0] + 1). "</span>";
$img = '/img/like.png';
}
else {
//echo "<div id='likes'><img id='likeimg' src='/img/dislike.png'>";
$query = "DELETE FROM likes WHERE id = $idlike[0]";
$result = mysqli_query($dbconfig, $query);
$query = "UPDATE restos SET likes = ($nrl[0]-1) WHERE id = $idresto";
$result = mysqli_query($dbconfig, $query);
//echo "<span id='likenr'> " . ($nrl[0] - 1). "</span></div>";
echo "<span id='likenr'> " . ($nrl[0] - 1). "</span>";
$img = '/img/dislike.png';
}
}
?>
Related
Hi I've made a messaging feature,it displays the receivers of the message in an account, beside the receiver's name is a green or red dot, for online or offline, it is successful when I log in 2 accounts and messaged each other, when I open the first account, the other account is offline, when I open the second account, the other is online, what my problem is I want to update their status in every five seconds so that their dot will be accurate whenever they log out or log in. I have made a javascript and ajax below this page left-col.php and I've tried copying the whole code, putting it to updating.php but it did not work, what should be the appropriate data inorder to update user receiver status in every 5 seconds inside the updating.php? and also, does my the javascript and ajax needs a library to be included that's why it didn't work? Please help.
<?php
require('connection.php');
$user_name=$_SESSION['username'];
$user_id=$_SESSION['user_id'];
if(!isset($_SESSION['user_id'])){
header("LOCATION: index.php");
}else{
$advance_time=time()+15;
$query=mysqli_query($con,"SELECT * FROM status WHERE user_id='$user_id'");
if(mysqli_num_rows($query)>0){
mysqli_query($con,"UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
}else{
mysqli_query($con,"INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
}
?>
<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById('new-message').style.display='block'" class="white-back">
<p align="center">New Message </p>
</div>
<?php
$q='SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="'.$_SESSION['username'].'" OR
`receiver_name`="'.$_SESSION['username'].'"
ORDER BY `date_time` DESC';
$e='SELECT * from messages';
$r=mysqli_query($con,$q);
if($r){
if(mysqli_num_rows($r)>0){
$counter=0;
$added_user=array();
while($row=mysqli_fetch_assoc($r)){
$sender_name=$row['sender_name'];
$receiver_name=$row['receiver_name'];
$timestamp=$row['date_time'];
if($_SESSION['username']==$sender_name){
//add the receiver_name but only once
//so to do that check the user in array
if(in_array($receiver_name,$added_user)){
//dont add receiver_name because
//he is already added
}else{
//add the receiver_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php
echo ''.$receiver_name.'';
$fetch_content=mysqli_query($con,"SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while($row_fetch=mysqli_fetch_array($fetch_content)){
$time=$row_fetch[5];
if($time<= time()){
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
}else{
$status= "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user=array($counter=>$receiver_name);
//increment the counter
$counter++;
}
}elseif($_SESSION['username']==$receiver_name){
//add the sender_name but only once
//so to do that check the user in array
if(in_array($sender_name,$added_user)){
//dont add sender_name because
//he is already added
}else{
//add the sender_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php echo ''.$sender_name.'';
$fetch_content=mysqli_query($con,"SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while($row_fetch=mysqli_fetch_array($fetch_content)){
$time=$row_fetch[5];
if($time<= time()){
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
}else{
$status= "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user=array($counter=>$sender_name);
//increment the counter
$counter++;
}
}
}
}
else{
//no message sent
echo 'no user';
}
}else{
//query problem
echo $q;
}
?>
<!-- end of left-col-container -->
</div>
<input type="hidden" value="<?php echo $user_id; ?>" id="from_user_id">
<script type="text/javascript">
setInterval(function(){updating_status()},5000);
function updating_status(){
let this_user = $('#from_user_id').val();
$.ajax({
method: "POST",
url: "updating.php",
data: {from_user:this_user},
success: function(response){
$('#content').html(response);
}
});
}
</script>
You need to handle the $_SESSION in all pages
Updating.php code:
<?php
require('connection.php');
session_start();
$user_name = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
if(isset($_REQUEST['from_user'])){
$advance_time=time()+15;
$user_id = $_REQUEST['from_user'];
$query=mysqli_query($con,"SELECT * FROM status WHERE user_id='$user_id'");
if(mysqli_num_rows($query)>0){
mysqli_query($con,"UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
}
}else{
mysqli_query($con,"INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
$html_left_div = '';
$html_left_div .='<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById(\'new-message\').style.display=\'block\'" class="white-back">
<p align="center">New Message </p>
</div>';
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$e = 'SELECT * from messages';
$r = mysqli_query($con, $q);
// echo $q;
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$timestamp = $row['date_time'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
$html_left_div .='<div class="grey-back first">
<img src="s.jpg" class="image"/>
' . $receiver_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id` WHERE user_name = '$receiver_name'");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status ='<img src=\'r.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
} else {
$status ='<img src=\'a.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
}
}
$html_left_div .= $status.'</div>';
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
$html_left_div .='<div class="grey-back second">
<img src="s.jpg" class="image"/>
' . $sender_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id` WHERE user_name = '$sender_name'");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status ='<img src=\'r.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
} else {
$status ='<img src=\'a.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
}
}
$html_left_div .= $status.'</div>';
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo 'no user';
}
} else {
//query problem
echo $q;
}
$html_left_div .='</div>';
echo $html_left_div;
Left-col.php code:
<?php
require 'connection.php';
session_start();
$user_name = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
if (!isset($_SESSION['user_id'])) {
header("LOCATION: index.php");
} else {
$advance_time = time() + 15;
$query = mysqli_query($con, "SELECT * FROM status WHERE user_id='$user_id'");
if (mysqli_num_rows($query) > 0) {
mysqli_query($con, "UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
} else {
mysqli_query($con, "INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
}
?>
<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById('new-message').style.display='block'" class="white-back">
<p align="center">New Message </p>
</div>
<?php
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$e = 'SELECT * from messages';
$r = mysqli_query($con, $q);
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$timestamp = $row['date_time'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php
echo '' . $receiver_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
} else {
$status = "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php echo '' . $sender_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
} else {
$status = "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo 'no user';
}
} else {
//query problem
echo $q;
}
?>
<!-- end of left-col-container -->
</div>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<input type="hidden" value="<?php echo $user_id; ?>" id="from_user_id">
<script type="text/javascript">
setInterval(function(){updating_status()},5000);
function updating_status(){
let this_user = $('#from_user_id').val();
$.ajax({
method: "POST",
url: "updating.php",
data: {from_user:this_user},
success: function(response){
$('#left-col-container').html(response);
}
});
}
</script>
Flow of the program:
1. Upon load of the page, the chart will display the total sales of all the branches.
2. When you choose a branch from the dropdown button, the data shown by the chart is the total sales of that specific branch.
My problem is when I click an specific branch the data wont show at all.
Please refer to the screenshot and Code for more information.
Screenshot:
Screenshot of the page when it loads
Screenshot of the page when I choose a branch
PHP Code for data:
<div class="report-header">
<h5 class="report-title">Total Yearly Sales</h5>
<div class="branch-report">
<select class="form-control" id="t-yearly">
<option value="">Branch</option>
<?php
require_once "connect.php";
$sql = "SELECT id,branch FROM tblLocation";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['id']."'>".$row['branch']."</option>";
}
?>
</select>
</div>
</div>
<div id="t-yearly-sales" style="height: 80%;"></div>
<?php
include "connect.php";
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
$chart = '';
while ($row = mysqli_fetch_array($result)){
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
?>
<script>
new Morris.Bar({
element: 't-yearly-sales',
data: [<?php echo $chart; ?>],
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
</script>
AJAX Code:
//Total Yearly Sales
$("#t-yearly").change(function(){
var branch = $(this).val();
$.ajax ({
url:"fetch_yearly_sales.php",
method: "POST",
data: {branch:branch},
success: function(branch_data){
new Morris.Bar({
element: 't-yearly-sales',
data: [branch_data],
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
console.log(branch);
}
});
});
Fetch_Yearly_Sales.php Code:
<?php
require "connect.php";
$data = mysqli_real_escape_string($conn,$_POST['branch']);
if($data == ""){
$output = "";
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
ob_clean();
echo $output;
}
else{
$output = "";
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales WHERE branch_id='".$data."' GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
ob_clean();
echo $output;
}
?>
You can try this in PHP
if($data == ""){
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$chart = '{year:'.$row["year"].', sales:'.$row["sales"].'},';
}
echo $chart;
} else {
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales WHERE branch_id='".$data."' GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$chart = '{year:'.$row["year"].', sales:'.$row["sales"].'}';
}
echo $chart;
}
The last comma is invalid. You should really consider using json_encode.
while ($row = mysqli_fetch_assoc($result)) {
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
echo $output;
Also you're not printing anything:
$output = "";
echo $output;
but you use $chart .= ""; to prepend data.
json_encode example:
$arr = array();
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
echo json_encode( $arr );
Whole ajax example:
require "connect.php";
$data = mysqli_real_escape_string($conn,$_POST['branch']);
if($data == ""){
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
$arr = array();
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
echo json_encode( $arr );
}
else{
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales WHERE branch_id='".$data."' GROUP BY year";
$result = mysqli_query($conn, $sql);
$arr = array();
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
echo json_encode( $arr );
}
A benefit can be assigned to an employee but firstly the code below shows the dynamic dropdown of employee and dynamic benefit checkboxes
<?php
$ctr = 0;
$employee = mysqli_query($conn, "SELECT * FROM housekeeping_employee") or DIE("Could not Select");
echo "<select class='indent' name = 'Employee'>";
while($listEmployee = mysqli_fetch_array($employee))
{
echo "<option value = ".$listEmployee['employeeid'].">".$listEmployee['firstname']."</option>";
}
echo "</select>";
echo "<br><be>";
echo "<div class='indent'>";
$benefits = mysqli_query($conn, "SELECT * FROM housekeeping_benefit")or DIE("SELECT Query not working.");
if(mysqli_num_rows($benefits))
{
while($row = mysqli_fetch_array($benefits))
{
$ctr++;
echo "<h6><input type = 'checkbox' name = 'benefits".$ctr."' value ='".$row['benefitid']."' >".$row['benefitname']." </input></h6> <be>";
if($ctr == 5){
echo"<br>";
$ctr=0;
}
}
echo "<br><input type='submit' class='btn btn-info' name='insert' value='Submit'/>";
}
echo "<input type='hidden' name='ctr' value='".$ctr."'/>";
echo "</form>";
?>
This is what the insert code of assigning benefits to employee looks like.
$employeeid = $_POST['Employee'];
for($a = 1; $a <= $_POST['ctr'] ; $a++)
{
if(isset($_POST['benefits'.$a]))
{
$benefitid = $_POST['benefits'.$a];
//echo "INSERT INTO `housekeeping_employeebenefits`(`employeeid`,`benefitid`) VALUES('$employeeid','$benefitid')";
mysqli_query($conn, "INSERT INTO `housekeeping_employeebenefits`(`employeeid`,`benefitid`) VALUES('$employeeid','$benefitid')") or DIE("Insert query is not working");
echo "Employee to Benefits successful!";
}
}
My main problem is how will I display checked checkboxes if the employee already has that benefit? I'm really lost
My JavaScript/AJAX prints comments. It's all good, until I want to insert/get more than one comment. It duplicates itself. This feels like a nesting/missed parenthesis problem in my code, but I can't be able to find it...
My JS code:
$(document).ready(function(){
var url = 'comment-get.inc.php';
$.getJSON(url, function(data) {
$.each(data, function(index, item) {
var t = '';
t += '<div class="comment_holder" id="_'+item.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+item.username+'<br>';
t += ''+item.date+'<br>';
t += '<button class="button2" type="button" id="'+item.id+'">Delete</button>';
t += '</div></div>';
t += ''+item.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
});
});
add_delete_handlers();
$('#postButton').click(function(){
comment_post_btn_click();
});
function comment_post_btn_click()
{
//text in textarea with username, page and date
var _username = $('#postUsername').val();
var _page = $('#postPage').val();
var _date = $('#postDate').val();
var _message = $('#postMessage').val();
if(_message.length > 0)
{
//proceed with ajax callback
$('#postMessage').css('border', '1px solid #ABABAB');
$.post("comment-set.inc.php",
{
task : "comment-set",
username : _username,
page : _page,
date : _date,
message : _message
}
).success(
function(data)
{
//Task: Insert html into the div
comment_set(jQuery.parseJSON(data));
console.log("ResponseText: " + data);
});
}
else
{
//text in area is empty
$('#postMessage').css('border', '1px solid #FF0000');
console.log("Comment is empty");
}
//remove text after posting
$('#postMessage').val("");
}
function add_delete_handlers()
{
$('.button2').each(function()
{
var btn = this;
$(btn).click(function()
{
comment_delete(btn.id);
});
});
}
function comment_delete(_id)
{
$.post("comment-del.inc.php",
{
task : "comment-del",
id : _id
}
).success(
function(data)
{
$('#_' + _id).detach();
});
}
function comment_set(data)
{
var t = '';
t += '<div class="comment_holder" id="_'+data.comment.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+data.comment.username+'<br>';
t += ''+data.comment.date+'<br>';
t += '<button class="button2" type="button" id="'+data.comment.id+'">Delete</button>';
t += '</div></div>';
t += ''+data.comment.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
}
});
Comments.php:
<?php
class Comments {
public function set($message, $username, $date, $page) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "INSERT INTO comments VALUES ('', '$username', '$page', '$date', '$message')";
$query = mysqli_query($connect, $sql);
if($query){
$std = new stdClass();
$std->id = mysqli_insert_id($connect);
$std->message = $message;
$std->username = $username;
$std->date = $date;
$std->page = $page;
return $std;
}
return null;
}
public function del($id) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "DELETE FROM comments WHERE id = $id";
$query = mysqli_query($connect, $sql);
if($query)
{
return true;
}
}
}
?>
Comment-get.inc.php:
<?php
$page = htmlentities("/index.php?page=maplepancakes", ENT_QUOTES);
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "SELECT * FROM comments WHERE page='$page' ORDER BY id DESC";
$result = $connect->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$row_data = array(
'id' => $row['id'],
'username' => $row['username'],
'date' => $row['date'],
'message' => $row['message']
);
array_push($data, $row_data);
}
?>
<?php
echo json_encode($data);
?>
Comment-set.inc.php:
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-set'){
$username = $_POST['username'];
$date = $_POST['date'];
$page = $_POST['page'];
$message = $_POST['message'];
require_once 'comments.php';
if(class_exists('Comments')){
$userInfo = $username;
$commentInfo = Comments::set($message, $username, $date, $page);
$std = new stdClass();
$std->user = $userInfo;
$std->comment = $commentInfo;
echo json_encode($std);
}
}
?>
Picture of the problem (json_encode in the bottom of the picture containing 3 comments):
your comments div container has class .comment_holder so each time with new comment you prepend to all class's so create comment container with unique id an prepend to this. like this $('#comment_container').prepend(t); this with work.
this is my code for dropdown list
<?php
$sql = "SELECT * FROM parts";
$result = mysql_query($sql);
echo "<select name='name' class='ed'>";
echo "<option id='0'> --Select Part Name-- </option>";
while ($row = mysql_fetch_array($result)) {
$op1=$row['part_description'];
$op2=$op1.$row['price'];
$op3=$op2.$row['weight'];
echo "<option value='" . $row['part_description'] ."'>" .$op3 ."</option>";
echo $op3;
}
echo "</select>";
?>
I have 3 columns for my database
part_description, price and weight. In the dropdownlist i created, you can select stored items at part_description. What I want to do is if I select that item in drop down list it will also display also the price and weight. But the display should be out of the box.
Please help me thanks
<?php
$sql = "SELECT part_description FROM parts";
$result = mysql_query($sql);
echo "<select name='name' class='ed'>";
echo "<option id='0'> --Select Part Name--</option>";
while ($row = mysql_fetch_array($result)) {
$op1=$row['part_description'];
$op2=$op1.$row['price'];
$op3=$op2.$row['weight'];
echo "<option value='" . $row['part_description'] ."'>" .$op3 ."</option>";
}
echo "</select>";
?>
This is for print three value in single option tag.
And let me know Is this your expectation.
You can do it in Javascript.
<?php
$parts = mysqli_query($conn, "SELECT part_description, price, weight FROM parts");
$theParts = [];
while ($row = mysqli_fetch_assoc($parts)) {
$part = [];
$part['description'] = $row['part_description'];
$part['price'] = $row['price'];
$part['weight'] = $row['weight'];
$theParts[] = $part;
}
?>
<script type="text/javascript">
var theParts = <?php echo(json_encode($theParts));?>;
function createDropDown() {
var theDropdown = "<select name='name' id='theDropDown' class='ed' onchange='didChange()'>";
theDropdown += "<option value='0'>--Select Part Name--</option>";
theParts.forEach(function(entry) {
theDropdown += "<option value='" + entry['description'] + "'>" + entry['description'] + "</option>";
});
theDropdown += "</select>";
return theDropdown;
}
function didChange() {
var e = document.getElementById("theDropDown");
var str = e.options[e.selectedIndex].value;
var price = null;
var weight = null;
theParts.forEach(function(entry) {
if (entry['description']==str) {
price = entry['price'];
weight = entry['weight'];
}
});
}
</script>
(I typed this code directly into StackOverflow and haven't tested it but it should work)
EDIT:
Here's how to do it using MySQL, although I don't recommend using it.
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('database', $conn);
$results = mysql_query("SELECT part_description, price, weight FROM parts");
while ($row = mysql_fetch_assoc($results)) {
//Same as above.
}