This is my output, clicking like button should add +1 to the likes column in MySQL .
I use a while loop to iterate buttons
For example, the "button" is displayed multiple times in the picture below. I have a tag in the while loop, so it outputs the button several times. And that name comes from the database.
MY Question. All the buttons in the will have the same ID. Currently, the user can only click the first button. I would like to give each element a different ID if possible. Then I would like to use jQuery to add a click event. So, if I click on the 4th button, the like count for that comment should be increased.
What I need.
How I can assign a different ID to each element in the far loop, so it does only make the first Image clickable but instead all elements' clickables?
<?php
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="single-item">
<div class="cmt_user"><div class="circle2">
<h5>
<?php
$name = $row['name'];
$f_letter = strtoupper($name[0]);
echo $f_letter;
?>
</h5>
</div>
<h4><?php echo $row['name']; ?></h4>
</div>
<p><?php echo $row['comment']; ?></p><div class="lcr">
<ul>
<li id = "modified" > </li>
</ul>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" class="form">
<button onclick="imageClick(<?php echo $row['id_vnr']; ?>)" name="like" value="<?php echo $row['id'] ?>" class="like_btn"><i class="fa fa-heart"></i> Like</button>
</form>
this is Php Code to insert likes count
<?php
$like = $_POST['like'];
if($like){
$sql = "UPDATE comments set likes = likes + 1 where id = '".$row['id']."'";
echo $sql;
$result=mysqli_query($link,$sql);
}
?>
It's really simple. do it like this
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="single-item">
<div class="cmt_user"><div class="circle2">
<h5>
<?php
$name = $row['name'];
$f_letter = strtoupper($name[0]);
echo $f_letter;
?>
</h5>
</div>
<h4><?php echo $row['name']; ?></h4>
</div>
<p><?php echo $row['comment']; ?></p><div class="lcr">
<ul>
<li id = "modified" > </li>
</ul>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" class="form">
<input name="like" value="1">
<input name="row_id" value="<?php echo $row['id'] ?>">
<button class="like_btn"><i class="fa fa-heart"></i> Like</button>
</form>
And get POST values like this
<?php
$like = $_POST['like'];
$row_id = $_POST['row_id'];
if(isset($like) && $like == 1){
$sql = "UPDATE comments set likes = likes + 1 where id = '".$row_id."'";
echo $sql;
$result=mysqli_query($link,$sql);
}
?>
Related
I am trying to make a filter for a website for cars. I would like to be able to filter by exterior color. I use exterior to represent my color in the database. My UL puts all color from the database into the box and makes each one a induvial check box. Then I have my page that list of all cars through a SELECT * Statement and then I fetch my results through individual echo statements that are wrap and a div. I Do not want to display my exterior colors name next to each car on this page since I am designing a mobile version and trying to keep it clean. However I have tried to list them as induvial tags and I still get send to a blank page.
<ul class="list-group">
<?php
$sql = "SELECT DISTINCT exterior FROM newcars ORDER BY exterior";
$result = $conn->query($sql);
while($row=$result->fetch_assoc()) {
?>
<li class="list-group-item">
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input product_check" name="" value="<?= $row['exterior']; ?>" id="exterior"><?= $row['exterior']; ?>
</label>
</div>
</li>
<?php
}
?>
</ul>
<div id="test">
<?php
$sql = "SELECT * FROM newcars";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo ("<a href='newcarindex.php?id={$row['id']}'><div class='car'>");
echo '
<tr>
<td>
<img src="data:image\jpeg;base64,'.base64_encode($row['photo']).'"/>
</td>
</tr>
';
echo "<h2 class=car-name>";
echo $row['name'];
echo "</h2>";
echo "<span class=stock>STOCK#";
echo $row['stock'];
echo "</span>";
echo "<h3 class=car-msrp>";
echo $row['msrp'];
echo "</h3>";
echo "</div></a>";
}
} else {
echo "There are no matching results!";
}
?>
</div>
this then leads into my ajax script
<script type="text/javascript">
$(document).ready(function(){
$(".product_check").click(function(){
$("#loader").show();
var action = 'data';
var class = get_filter_text('class');
var body = get_filter_text('body');
var exterior = get_filter_text('exterior');
$.ajax({
url:'action.php',
method:'POST',
data:{action:action,class:class,body:body,exterior:exterior},
success:function(response){
$("#test").html(response);
$("loader").hide();
}
});
});
function get_filter_text(text_id){
var filterData = [];
$('#'+text_id+':checked').each(function(){
filterData.push($(this).val());
});
return filterData;
}
});
</script>
and Finally use a action.php page to connect to my database and filter the results
include 'dbh.php';
if(isset($_POST['action'])) {
$sql = "SELECT * FROM newcars WHERE class !=''";
if(isset($_POST['exterior'])) {
$exterior = implode("','", $_POST['exterior']);
$sql .="AND exterior IN('".$exterior."')";
}
$result = $conn->query($sql);
$output='';
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$photo = base64_encode($row['photo']);
$output .= "<a href='newcarindex.php?id={$row['id']}'>
<div class='car'>
<tr>
<td>
<img src='data:image\jpeg;base64,{$photo}'/>
</td>
</tr>
<h2 class='car-name'>{$row['name']}</h2>
<span class='stock'>STOCK#{$row['stock']}</span>
<h3 class='car-msrp'>{$row['msrp']}</h3>
</div></a>";
}
echo $output;
}
} else {
echo "There are no comments!";
}
}
?>
The Problem I have is every time i click on a color to filter by my page comes up blank showing no results or errors. What am I doing wrong?
just looking at the action.php, upon a successful query, I don't see $output being echoed. Is this the complete code for the action.php?
include 'dbh.php';
if(isset($_POST['action'])) {
$sql = "SELECT * FROM newcars WHERE class !=''";
if(isset($_POST['exterior'])) {
$exterior = implode("','", $_POST['exterior']);
$sql .="AND exterior IN('".$exterior."')";
}
$result = $conn->query($sql);
$output='';
if($result->num_rows>0){
while($row=$result->fetch_assoc()) {
$photo = base64_encode($row['photo']);
$output .= "<a href='newcarindex.php?id={$row['id']}'>
<div class='car'>
<tr>
<td>
<img src='data:image\jpeg;base64,{$photo}'/>
</td>
</tr>
<h2 class='car-name'>{$row['name']}</h2>
<span class='stock'>STOCK#{$row['stock']}</span>
<h3 class='car-msrp'>{$row['msrp']}</h3>
</div></a>";
}
echo $output;
} else {
echo "There are no comments!";
}
}
?>
```
Im working on a confession website, and on the website I have a section "Top of the Week" which displays 3 most liked confessions from current week, it displays them in a horizontal slider by most liked order, so it goes most liked, second most liked, third most liked confession. The thing that Im trying to do is to put #1, #2, #3 number on each one, but I can't achieve that because I only style one div and website automatically create two other and add confession to it.
This is my php + html code that I use to display them:
<div class="sidebox">
<?php
$select = "SELECT confessions.confessId,
(IFNULL(confessions.firstName, '')) AS firstName,
confessions.confessText,
DATE_FORMAT(confessions.postDate,'%b %d %Y %h:%i %p') AS postDate,
hasImage,
UNIX_TIMESTAMP(confessions.postDate) AS orderDate,
confessions.isActive,
(SELECT COUNT(*) FROM views WHERE views.confessId = confessions.confessId ) as totalViews,
(SELECT COUNT(*) FROM likes WHERE likes.confessId = confessions.confessId ) as totalLikes,
(SELECT COUNT(*) FROM dislikes WHERE dislikes.confessId = confessions.confessId ) as totalDislikes
FROM
confessions
WHERE isActive = 1
ORDER BY totalViews DESC , orderDate DESC limit 3";
$resss = mysqli_query($mysqli, $select) or die('-3' . mysqli_error()); ?>
<div id="sticky-nav" style="height:36px;" class="absolute" style="z-index:0">
<div id="width-limit">
<div class="options">
<ul class="menu">
<li><a class="carousel_prev previous" href="#"><b style="font-size: 20px;">‹</b></a></li>
<li><a style="opacity:1;padding-top:1px;position:relative;left:-54px;"><i class="fas fa-crown" id="crownicon"></i> Top of the Week</a> </li>
<li><div class="menu-clear"></div></li>
<li><a class="carousel_next next" href="#"><b style="font-size: 20px;">›</b></a></li>
</ul>
</div>
<div class="options" id="opt2" style="float:right; width:280px;display:none;">
<ul style="display: inline-block;float:right;">
</ul>
</div><div class="options" id="opt2" style="float:right; width:280px;display:none;">
<ul style="display: inline-block;float:right;">
</ul>
</div>
<div id="small-logo"></div>
<div class="clearfix"></div>
</div>
</div><div class="sidecontainer">
<div class="slick">
<?php
while ($row = mysqli_fetch_assoc($resss)) {
// Get Total Comments
$comssql = "SELECT 'X' FROM comments WHERE confessId = ".$row['confessId']." AND isActive = 1";
$commentstotal = mysqli_query($mysqli, $comssql) or die('-4'.mysqli_error());
$totComments = mysqli_num_rows($commentstotal);
if ($totComments == '1') { $comText = 'Comment'; } else { $comText = 'Comments'; }
if ($row['totalViews'] == '1') { $viewText = 'View'; } else { $viewText = 'Views'; }
$shareURL = $set['installUrl'].'page.php?page=view&confession='.$row['confessId'];
?>
<div class="confession" style="margin-left: 0;width: 300px;">
<div class="left"><span class="label2 label-confess1"><?php echo $row['totalViews'].' '.$viewText; ?></span></div>
<div class="right"><span class="bestthisweek">
<?php if ($row['totalLikes'] == '12') { echo "Top of the Day!"; } else { echo "Top!"; } ?>
</span></div>
<div class="confessionstyle" style="margin-top:20px;"><p>
<font color="#fff3b2">
<?php
if ($filterProfanity == '1') {
echo nl2br(htmlspecialchars(filterwords($row['confessText'])));
} else {
echo nl2br(htmlspecialchars($row['confessText']));
}
?>
</font>
</p></div>
<input type="hidden" id="confessId" name="confessId_<?php echo $count; ?>" value="<?php echo $row['confessId']; ?>" />
<?php
$chkLikes = mysqli_query($mysqli,"SELECT 'X' FROM likes WHERE confessId = ".$row['confessId']." AND likeIp = '".$_SERVER['REMOTE_ADDR']."' LIMIT 1");
$hasLike = mysqli_num_rows($chkLikes);
$likeCSS = $hasLike > 0 ? 'text-info' : 'white';
$chkDislikes = mysqli_query($mysqli,"SELECT 'X' FROM dislikes WHERE confessId = ".$row['confessId']." AND dislikeIp = '".$_SERVER['REMOTE_ADDR']."' LIMIT 1");
$hasDislike = mysqli_num_rows($chkDislikes);
$dislikeCSS = $hasDislike > 0 ? 'text-danger' : 'white';
?>
<div class="confession-actions">
<div class="likes" style="width: 75px;">
<span class="label2 label-confess first liked">
<a href="" id="likeIt_<?php echo $row['confessId']; ?>" class="likeIt_<?php echo $count; ?> <?php echo $likeCSS; ?>" style="text-decoration:none;outline:none;">
<i class="fas fa-thumbs-up"></i> <span style="color:white;" id="likesVal_<?php echo $row['confessId']; ?>"><?php echo $row['totalLikes']; ?></span>
</a>
</span>
</div>
<div class="dislikes" style="width: 75px;">
<span class="label2 label-confess disliked">
<a href="" id="dislikeIt_<?php echo $row['confessId']; ?>" class="dislike_<?php echo $count; ?> <?php echo $dislikeCSS; ?>" style="text-decoration:none;outline:none;">
<span style="color:white;" id="dislikesVal_<?php echo $row['confessId']; ?>"><?php echo $row['totalDislikes']; ?></span> <i class="fas fa-thumbs-down"></i>
</a>
</span>
</div>
<?php if ($row['hasImage'] != '0') { ?>
<span class="label label-confess"><i class="fa fa-picture-o img"></i></span>
<?php } ?>
<div class="comments">
<div class="divide" style="width: 75px;"><div id="comments-hvr"><a href="page.php?page=view&confession=<?php echo $row['confessId']; ?>">
<i class="fa fa-comments"></i> <?php echo $totComments.' '; ?>
</a></div></div>
</div>
<div class="divide2" style="width: 75px;"><div class="fb-share-button" style="top:-6.5px;transform: scale(0.93);"
data-href="page.php?page=view&confession=<?php echo $row['confessId']; ?>"
data-layout="button_count"></div></div></div>
<div class="clearfix"></div>
</div>
<?php
}
?>
</div>
I tried everything and this is the best solution that I have, but I can't figure out what should I put inside if, elseif, else, I need something that will place #1 on first, #2 on second, #3 on third confession. So I would need something like this but something that will not require me to manually insert > likes.
<?php if ($row['totalLikes'] > '11') { echo "#1"; } elseif ($row['totalLikes'] > '5') { echo "#2"; } else { echo "#3"; }?>
Please visit my website, its still in development, but check Top of the Week on the right and you'll have a clue of what I actually want: http://confessions.byethost31.com
FINAL:
<?php $i = 1; ?>
<?php
echo '#'.$i;
$i++;
?>
Easiest way to to just create a variable that increments with every while iteration.
$i = 1; // set initial value
while ($row = mysqli_fetch_assoc($resss)) {
echo 'This number will grow by 1 for every row - '.$i;
$i++; // this is equal to $i = $i + 1; so will increment by 1 every time.
}
EDIT:
Instead of attempting to assume what the total likes would be, it would be easier to sort them by total likes (putting the most liked first and assigning this #1).
ORDER BY totalLikes DESC, totalViews DESC, orderDate DESC
You can then just use
echo '#'.$i;
Where you want to display the number, you can do this because you have LIMIT 3 so only the top 3 will display.
Objective Inserting name(input-text) and info(textarea-contains multiple lines) into the database, and after submission of the form, at the same page, 2 columns are for displaying the same data in columns, name & info, but under info column. I have made buttons for each row in front of the names, which is used as slideToggle for showing/hiding which contains the data retrieved from the 'info' column
Problem - when I am clicking the button of 1st row, instead of displaying the info related to 1st entry only, it is sliding and showing all info(s) related to all entries at only click.
*others - one more input has been added to the form but as hidden used for id(auto increment)
----index.php-----
<?php include('php_code.php'); ?>
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM records WHERE id=$id");
if (count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$name = $n['name'];
$acc = $n['acc_no'];
$info = $n['info'];
}
}
?>
<html>
<head>
<title>JSK</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('form').hide();
$('p').hide();
$('#sp').hide();
$("#inf").click(function(){
$("p").slideToggle();
$('#sp').slideToggle();
});
$("#fo").click(function(){
$("form").slideToggle();
});
});
</script>
</head>
<body>
<div class="container">
<div class="left">
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
<?php $results = mysqli_query($db, "SELECT * FROM records"); ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Account No</th>
<th>Info</th>
<th colspan="2">Action</th>
</tr>
</thead>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['acc_no']; ?></td>
<td><button id="inf" onclick="myFunction()">show</button></td>
<td>
<a href="index.php?edit=<?php echo $row['id']; ?>" class="edit_btn" >Edit</a>
</td>
<td>
Delete
</td>
</tr>
<tr id="sp"> <td colspan="4"><p> <?php echo $row['info']; ?> </p></td>
</tr>
<?php } ?>
</table>
<div id="fotable" align="center">
<button id="fo">Add New/Edit</button>
</div>
<form method="post" action="php_code.php" >
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>Name</label>
<input type="text" autocomplete="off" name="name" value="<?php echo $name; ?>">
</div>
<div class="input-group">
<label>Account No</label>
<input type="text" name="acc" value="<?php echo $acc; ?>">
</div>
<div class="input-group">
<label for="info">Info</label>
<textarea class="form-control" rows="8" name="info" id="info"><?php echo $row['info']; ?></textarea>
</div>
<div class="input-group">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Add Account</button>
<?php endif ?>
</div>
</form>
</div><!-- left closed -->
<div class="right">
hello
</div> <!-- right closed -->
</div> <!-- container closed -->
</body>
</html>
---php_code.php-----
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'jskrecords');
// initialize variables
$name = "";
$acc = "";
$info = "";
$id = 0;
$update = false;
if (isset($_POST['save'])) {
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "INSERT INTO records (name, acc_no, info) VALUES ('$name', '$acc', '$info')");
$_SESSION['message'] = "Account saved";
header('location: index.php');
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "UPDATE records SET name='$name',acc_no='$acc',info='$info' WHERE id=$id");
$_SESSION['message'] = "Account updated!";
header('location: index.php');
}
if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM records WHERE id=$id");
$_SESSION['message'] = "ACC deleted!";
header('location: index.php');
}
?>
Concept:
If you are creating multiple form from same mysql table using php script, You need to give each form a unique id.
e.g.
<form method="post" action="php_code.php" id="form<?= $id ?>">
Then add data-target="#form" to button with class 'inf'. It will store id of form.
<button class="inf" data-target="#form<?= $id ?>">show</button>
When button is clicked we know which form to open from data-target.
<script>
$('.container').on('click','button.inf',function(e){
e.preventDefault();
var formid=$(this).attr('data-target'); //get value of data-target attribute
//...proceed to play toggle with this form 'formid'
I am trying to pass hidden value from page to another page and it work fine only for first record however for other records it's showing error
Here is the code:
$sql = "SELECT id,jdes,title FROM job";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<input type="hidden" id="hidden_user_id" value="<?php echo $row["id"] ?>">
<h3><?php echo $row["title"] ?>:</h3>
<p class="lead">
<?php echo $row["jdes"] ?>
</p>
<button type="button" id="requestthis" class="btn btn-primary">
Request
</button>
<?php
}
} else {
echo "Nothing to display Yet";
}
?>
jobs-inner.php
<?php
echo $_GET['hidden_id'];
?>
Javascript:-
$(function() { //ready function
$('#requestthis').on('click', function(e){ //click event
e.preventDefault();
var hidden_id = $('#hidden_user_id').val();
var url = "jobs-inner.php?hidden_id="+hidden_id;
window.location.replace(url);
})
})
Error:-
Undefined index: hidden_id in C:\wamp64\www\project\jobs-inner.php on line 3
It might be a simple problem but I am a beginner and I can't figure it out.
Your value is unique but the id isn't. Make the id of the input unique something like below.
<input type="hidden" id="hidden_user_<?php echo $row["id"] ?>" value="<?php echo $row["id"] ?>">
but you would have to do a count on code below to make it display base on how many rows you have.
<?php
echo $_GET['hidden_id'];
?>
Without JavaScript
$sql = "SELECT id,jdes,title FROM job";
$result = $conn->query($sql);
$count = 1;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<input type="hidden" id="hidden_user_<?php echo $count ?>" value="<?php echo $row["id"] ?>">
<h3><?php echo $row["title"] ?>:</h3>
<p class="lead"><?php echo $row["jdes"] ?></p>
<form id="<?php echo $count ?>" action="jobs-inner.php?hidden_id=<?php echo $row["id"] ?>" method="post">
<input type="submit" vaule="Request">
</form>
<?php
$count++;
}
} else {
echo "Nothing to display Yet";
}
?>
My code:
<?php
require_once 'core/init.php';
if($result = $db->query ("SELECT * from countries")) {
if($count = $result->num_rows) {
$rows = $result->fetch_all(MYSQLI_ASSOC);
}
}
?>
<div class="region">
<h1>Europe</h1>
<ul class="country" style ="list-style-type:none">
<?php foreach ($rows as $key => $row) { ?>
<li>
<a href=""=<?php echo $row['country_id']; ?>">
<a href=""=<?php echo $row['region_id']; ?>">
<?php echo $row['country_name']; ?></a> <br>
<?php
if (isset($_FILES['country_img']) === true) {
if (empty($_FILES['country_img']['name']) === true) {
echo 'please choose a file!';
print_r ($_POST);
} else {
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['country_img']['name'];
$file_extn = end(explode('.', $file_name));
$file_temp = $_FILES['country_img']['tmp_name'];
if (in_array($file_extn, $allowed) ===true) {
if ($_POST['id'] = $_POST['id']) {
addcountryimage($row['country_id'], $file_temp, $file_extn);
}
header ('Location: tes2.php');
break;
}else {
echo 'Incorrect file type. Allowed: ';
echo implode (', ', $allowed);
}
}
}
if (empty($row['country_img'] === false)) {
echo '<img src="', $row['country_img'], '" alt="', $row['country_name'], '\'s Image">';
}
?>
<p> <?php echo $row['country_bio']; ?></p>
<?php
global $session_user_id;
if (is_admin($session_user_id) === true) { ?>
<form action="" method="POST" name="" enctype="multipart/form-data">
<input type="hidden" name="id" id="hidden_id">
<input type="file" name="country_img"> <input type="submit" onclick="document.getElementById('hidden_id').value=$row['country_id']" />
</form>
<?php } ?>
<p> Tour to <?php echo $row['country_name']; ?></p>
</li>
<?php } ?>
</ul>
<h3> More European Country </h3>
</div>
Everything above works, except the fact that it can't differentiate between each submit button. For example, when I update the image on the 5th forms it will always update the 1st form. How can I do this?
The origin of your issue is using multiple id attributes with the same value in your JavaScript events, this is regarded wrong, every element id must be unique, beside this, onclick event with submit typed inputs of form is not working properly.
Add an incremental counter to your loop and then use to distinguish each form hidden element id.
<?php $i = 0;?>
<?php foreach ($rows as $key => $row) { ?>
....
<input type="hidden" name="id" id="hidden_id_<?php echo $i;?>">
....
<input type="submit" onclick="document.getElementById('hidden_id_<?php echo $i;?>').value=$row['country_id']" />
<?php
$i++;
} ?>
Another note, I think that onclick event does not works fine with submit type inputs, so I suggest to replace it with onsubmit event in the form itself as:
<form action="" method="POST" name="" enctype="multipart/form-data" onsubmit="document.getElementById('hidden_id_<?php echo $i;?>').value=$row['country_id']">