Before I say anything I'll just post my index.php to allow you guys to get an idea of what it looks like first:
<script>
function submitLikeForm() {
var form = jQuery("#like_form");
$.ajax({ type: "GET", url: form.attr("action"), data: form.serialize(), success: function() });
}
</script>
<script>
function leaveYourComment() {
var form = jQuery("#comment_form");
$.ajax({ type: "GET", url: form.attr("action"), data: form.serialize(), success: function() });
}
</script>
<link type="text/css" rel="stylesheet" href="index.css">
</head>
<body>
<?php
$conn = mysqli_connect("localhost","root","") or die ("No SQLI");//run query to display all images uploaded by users
mysqli_select_db($conn, "sample") or die ("No DB");
$sqli = "SELECT * FROM `photos` ORDER BY `id` DESC";
$result = mysqli_query($conn, $sqli) or die ("No query");
while($row = mysqli_fetch_assoc($result)) {
$username = $_SESSION['id'];
$title = $row['title'];
$description = $row['description'];
$image_name = $row['image_name'];
$random_directory = $row['random_direc'];
$date = date('M/d/Y');
$image_info = "http://localhost/splindr_2.0/photos/$random_directory/$image_name";
$sqli = ("SELECT * FROM `likes` WHERE `hidden_name` = '$image_name' AND `hidden_folder` = '$random_directory'");//run query to get likes
$likes_result = mysqli_query($conn, $sqli) or die ("No query");
$liked_count = '0' ; $unliked_count = '0';
while($likes_row = mysqli_fetch_assoc($likes_result)) {
if($likes_row['liked_unliked'] == 0) {
$unliked_count++;
} else {
$liked_count++;
}
}
$comment_count = ("SELECT * FROM `comments` WHERE `hidden_folder` = '$random_directory' AND `hidden_name` = '$image_name'");//run query to get comments
$comment_query = mysqli_query($conn, $comment_count) or die ("No query");
$total_comments = mysqli_num_rows($comment_query);
while($comment_result = mysqli_fetch_assoc($comment_query)) {
$comment = $comment_result['comment'];
$commented_on_by = $comment_result['commenting_user'];
}
echo "<div id='contentWrapper'>
<div class='photo'>
<div class='actual_image'>
<img src='$image_info'>
</div>
<div class='like_system'>
<form name='like_form' id='like_form' action='liked_button.php'>
<input type='image' img src='https://i.imgur.com/pMmYaYM.jpg' class='like_button button' name='like_button' onClick='return submitLikeForm()'>
<input type='hidden' name='hidden_image' class='hidden_image' value='$image_info'>
<input type='hidden' name='hidden_folder' class='hidden_folder' value='$random_directory'>
<input type='hidden' name='hidden_name' class='hidden_name' value='$image_name'>
<input disabled type='text' name='total_likes' class='total_likes' value='$liked_count'>
</form>
<a style='color: #2e4987;text-decoration:none' href='http://www.twitter.com/share?url=$image_info&hashtags=Splindr, CheckThisOut'>
<img class='twitter_button button' name='twitter_button' src='http://i.imgur.com/hKFKJoj.jpg'></a>
<img src='http://i.imgur.com/8azoFjh.jpg' class='show_comments button' name='show_comments'>
<input disabled type='text' class='comment_count' name='comment_count' value='$total_comments'>
<img class='delete_button button' name='delete_button' src='http://i.imgur.com/wKZu2H1.jpg'>
</div>
<div class='info_wrapper'>
<div class='info_header'>Title: $title   By: $username   Date: $date</div>
<div class='description'>$description</div>
</div>
<div class='comment_wrapper'>
<div class='close_comment'>[close comments]</div>
<div class='comment_box_wrapper'>
<div class='comment_box'>
<div class='commenter'>$commented_on_by</div>
<div class='profile_pic'><img src='https://i.imgur.com/1MkFvhU.png'></div>
<div class='actual_comment custom_scrollbar'>$comment</div>
</div>
</div>
<div class='post_comment'>
    <a style='color:#9b6bb4 ; text-decoration:none ; position:relative ; top:-5px ; left:-5px'></a>
<form name='comment_form' id='comment_form' action='leave_comments.php' onSubmit='return validateForm()'>
<input type='text' name='user_comment' class='user_comment' placeholder='Leave a comment...'>
<input type='hidden' name='hidden_image' class='hidden_image' value='$image_info'>
<input type='hidden' name='hidden_folder' class='hidden_folder' value='$random_directory'>
<input type='hidden' name='hidden_name' class='hidden_name' value='$image_name'>
<input type='image' img src='http://i.imgur.com/8azoFjh.jpg' class='leave_comment button' name='leave_comment button' onClick='return leaveYourComment ()'>
</form>
</div>
</div>
</div>
</div>";
}
?>
Okay so basically, so this index.php page is where images go after users upload them. Users can comment and like posts/images.
The problem I'm having is with my comments system. The comments are uploaded to mysqli just fine, however, I'm having trouble echoing each individual comment out. Multiple comments are shown in my table, but when I post a new comment, the new comment just replaces the previously posted comment. I don't want this, I want every comment to display by id DESC.
I've tried a loop for the comments (as you can see in the code above), but like I said, it just makes the newest comment replace the older comment.
So how can I correct my code so that all comments show in a comment_box within the comment_box_wrapper, with the respective information of the user that posted the comment.
I've struggled with this all day so any help will be appreciated.
Let me know if you need me to post anything else. I only posted the index.php because everything else is working and the problem is located only on this page.
You are assigning the $comment and $commented_by variables in a loop, effectively overwriting them, without using them.
You'd need to split you one big echo, and replace the comment_box part with something like this:
while($comment_result = mysqli_fetch_assoc($comment_query)) {
echo "<div class='comment_box'>";
echo "<div class='commenter'>".$comment_result['commenting_user']."</div>";
echo "<div class='profile_pic'><img src='https://i.imgur.com/1MkFvhU.png'></div>";
echo "<div class='actual_comment custom_scrollbar'>".$comment_result['comment']."</div>";
echo "</div>";
}
As you see above, we print each comment data, on each iteration of the loop.
Related
i want to add commenting to each article, so inside my"foreach"cycle I added commenting to each article, but "set a comment" function runs to all art
thats the code for making an article window
<?php $articles_qr = mysqli_query($connection, "SELECT * FROM `articles` ");
$articles = array();
while ( $art = mysqli_fetch_assoc($articles_qr))
{
$articles[] = $art;
}
?>
<?php foreach ($articles as $art)
{
?>
<section>
<div class="containerstuff">
<div class="stuffpic">
<img src="<?php echo "../static/imagespages/",$art['image'] ?>" class="pico">
</div>
<div class="article">
<h1><?php
echo $art['title']
?>
</h1>
<?php
echo $art['text'];
echo $art['id']
?>
</div>
</div>
<div class="scrollmenu">
<?php include "../includes/comments.php";?>
</section>
<?php
} ?>
thats the code comments window
<?php
date_default_timezone_set(timezone_identifier);
include_once '../comments.ink.php'
?>
<div class="containercom">
<img src="#" class="commpic">
<p class="comment"></p>
</div>
<div class="blockcom">
<form class='form' method='POST' action="<?php echo setComments($connection)?>">
<div class='form__group'>
<input type='hidden' name='page_id' value="<?php echo $art['id']?>" >
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='pubdate' value="<?php echo date('Y-m-d H:i:s')?>" >
<textarea name='text' class='form__control' placeholder ='Введите комментарий...' required=''></textarea>
</div>
<div class='form__group'>
<input type='submit' class='form__control2' name='commentSubmit'></input>
</div>
</div>
</form>
and thats the code for INSERT function
<?php
static $firstTime = true;
function setComments($connection) {
if(isset($_POST['commentSubmit'])){
$idcom = $_POST['page_id'];
$uid = $_POST['uid'];
$pubdate = $_POST['pubdate'];
$text = $_POST['text'];
$sql =
"INSERT INTO `comments` (page_id, uid, pubdate, text)
VALUES ('$idcom', '$uid', '$pubdate', '$text')";
$result = $connection->query($sql);
$firstTime = false;
}
}
so how can i make insert only for 1 article (so when i add it now, there are appears as many comments as many articles i have in database)
I think you should use ajax to append a new comment which is the widely used solution, the way u r doing will become difficult to handle for you.
I haven't found the solution, so I just selected another way.
For each article I placed a button to post a comment which will send user to the page with this article and for this button for "href" I wrote php code (href = "comments.php?id=<?php echo $art['id']"?>) and for this page I use $_GET to select articles only for this id. Then I just placed there comments-function that I wrote so it works alright now because function works only for 1 argument
This is the code I wrote to generate as many forms as there is entries in a table.
I'd like to know which Submit button (i.e. of which exact form) was clicked to then execute some SQL actions.
Thank you for your help!
<?php
require_once 'header.php';
if (!$loggedin) die();
$result = queryMysql("SELECT * FROM audit_requests");
$num_rows = $result->num_rows;
echo "<div class='main'><h3>$num_rows audit requests found!</h3>";
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$requester = stripslashes($row['user']);
$audit_request_id = stripslashes($row['audit_request_id']);
echo <<<_END
<form method='post' action='audit_listings.php' enctype='multipart/form-data'>
<span class='text'><br>Audit request number</span>
<input disabled type='text' maxlength='10' name='audit_request_id' value='$audit_request_id'>
<span class='text'><br>Auditee name</span>
<input disabled type='text' maxlength='16' name='user' value='$requester'>
_END;
if (getCategory($user) == 'Auditor')
{
echo "<input type='submit' value='Apply for this audit request'>";
}
echo <<<_END
</form></div><br>
_END;
}
if (isset($_POST['audit_request_id']))
{
$audit_request_id = stripslashes('audit_request_id');
queryMysql("INSERT INTO audit_plan SELECT * FROM audit_requests WHERE audit_request_id='$audit_request_id'");
queryMysql("UPDATE audit_plan SET applicant='$user' WHERE audit_request_id='$audit_request_id'");
queryMysql("INSERT INTO messages VALUES('', 'TrustusChain', '$org_name', '$address', '', '$city'");
}
?>
You could add a hidden field to the form. Like:
echo "<input type=\"hidden\" value=\"form_xxx\">";
You can generate random id's to the form like
<form method="post" onsubmit="return myfunc(this.id)" id="From_php">
in javascript
<script>
function myfunc(id){
//do anything with id of form
}
</script>
You can pass ajax requests to server accordingly.
I'm trying to implement some Ajax on a favourite/unfavourite button. The idea behind it is that when you click it a star changes to yellow and when you click it again, it changes back to grey and so on. It adds and deletes data from a DB.
before I had it like this
<?php
include("classes/event.class.php");
$m = new Event();
$arrayAllEvents = $m->getNonFavo();
$arrayFavorites = $m->getFavo();
$db = new db();
while ($row = mysqli_fetch_assoc($arrayFavorites))
{
$unfavoriteID = $row['f_id'];
$uid = $_SESSION['u_id'];
}
if(isset($_POST['favorite_row']))
{
$uid = $_SESSION['u_id'];
$Fid = $_POST['id_to_be_favo'];
if(!mysqli_query($db->conn, "INSERT INTO favorites (u_id, n_id, f_boolean) VALUES
('". $db->conn->real_escape_string($uid) ."' ,
'". $db->conn->real_escape_string($Fid) ."' ,
'". $db->conn->real_escape_string("1") ."')"))
{
echo mysqli_error($db->conn);
}
}
if(isset($_POST['Unfavorite_row']))
{
$unFid = $_POST['id_to_be_unfavo'];
if(!mysqli_query($db->conn, "DELETE FROM favorites WHERE f_id ='".$unFid."'"))
{
echo mysqli_error($db);
}
}
?>
And the field was a php echo form
<?php
echo "<form method='post'>
<input type ='hidden' name='id_to_be_favo'
value='".$a['n_id']."' />
<input type='submit' class='favoriteFalse' id='FavoBtn' name='favorite_row' value='favorite' />
</form>
<div class='clearfix'> </div>";
?>
I'm trying to change the form to a button and use jQuery/Ajax to switch it.
I've been trying some different solutions I've found online, but none of them seem to work.
What would be the best way to implement this?
Kind regards
<input type='button' class='favorite' id='<?php echo $a['n_id']; ?>' value='favorite' />
<div class='clearfix'> </div>";
using
$(function() {
$(".favorite").on("click".function() {
$.post("whatever.php", {"favorite_row":this.id}, function(data) {
$("#star").html('<img/>',{"src":data.fave==yes"?"true.png":"false.png"});
});
});
Now return {"fave":"yes"} if favorited
I am trying to edit data in my database but i cant get it to work.
i have tried breaking the script down to basics and troubleshoot each part.
The delete button works just fine but editting the data doesn't.
Where have i gone wrong?
my structure
database = domains table = domains_info row = domain
<?php include("header.php");
//include database connection
include 'db_connect.php';
$action = isset( $_POST['action'] ) ? $_POST['action'] : "";
if($action == "update"){
//write query
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."',
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
if( $mysqli->query($query) ) {
echo "User was updated.";
}else{
echo "Database Error: Unable to update record.";
}
}
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM domains_info WHERE id='".$mysqli->real_escape_string($_GET['id'])."'";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}}
$query = "select id, domain
from domains_info
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'
limit 0,1";
$result = $mysqli->query( $query );
$row = $result->fetch_assoc();
$id = $row['id'];
$domain = $row['domain'];?>
<form action='#' method='post' border='0' class="well form-horizontal">
<fieldset>
<label class="control-label" for="name">Domain</label>
<div class="controls">
<input id="name" type="text" name="name" value="<?php echo$domain; ?>">
<input type='hidden' name='id' value='<?php echo $id ?>' />
<!-- we will set the action to edit -->
<input type='hidden' name='action' value='update' />
<input type='submit' value='Edit' />
</fieldset>
</form>
<?php echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>"; ?>
<script type='text/javascript'>
function delete_user( id ){
//prompt the user
var answer = confirm('Are you sure you want to delete <?php echo$name; ?>?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id of the record to be deleted
window.location = 'deletecontact.php?id=' + id;
}
}
</script>
the error im getting is this
Database Error: Unable to update record.
There is a extra ',' in your update query
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."',
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
with
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."'
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
I'm working on an invoicing system. I'm using javascript to add line items as needed however the added line items are not posting when I click submit. I'm thinking it is probably an issue with div somewhere but I cannot seem to find it or get it to work. I'm posting my code for help. Thanks.
Here is my form.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";
$result = mysql_query("SELECT company, first, last FROM customer") or die (mysql_error());
?>
<script type="text/javascript">
var counter = 1;
function addInput(div){
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var newdiv = document.createElement('div');
newdiv.innerHTML = " Entry " + (++counter) + " <br /><table><tr><td>Item: <select name='item[]'>" + xmlhttp.responseText + "</select></td><td>Qty: <input name='quantity[]' type='text' size='5' /></td></tr></table><br />";
}
document.getElementById(div).appendChild(newdiv);
}
xmlhttp.open("GET", "dropdownquery.php", false);
xmlhttp.send();
}
</script>
<form id="createInvoice" method="post" action="docreateinvoice.php">
<table>
<tr><td>Customer</td><td><select name="company">
<?php while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['company']."\">".$row['company']." (".$row['first']." ".$row['last'].")</option>";
}
?>
</select></td></tr>
</table>
</div>
</div>
<div id="container">
<div class="content">
<div id="dynamicInput">
Entry 1<br /><table><tr><td>Item: <select name="item[]"><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select></td><td>Qty: <input name="quantity[]" type="text" size="5" /></td></tr></table><br />
</div>
<br /><input type="button" value="Add Line Item" onClick="addInput('dynamicInput');">
</div>
</div>
<div id="container">
<div class="content">
<input type="submit" name="submit" value="Create Invoice" />
</form>
<?php
include $_SERVER['DOCUMENT_ROOT']."/includes/footer.php";
?>
This next piece of code is dropdownquery.php. This is what gets the dropdown box data in the javascript. Big thanks to #NickSlash for figuring this out in the javascript.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$result = mysql_query("SELECT * FROM salesitem");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
?>
And finally, this is my docreateinvoice.php which I post to.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$company = mysql_real_escape_string($_POST['company']);
foreach($_POST['item'] as $i => $item)
{
$item = mysql_real_escape_string($item);
$quantity = mysql_real_escape_string($_POST['quantity'][$i]);
//mysql_query("INSERT INTO invoice (company, item, quantity) VALUES ('$company', '".$item."', '".$quantity."') ") or die(mysql_error());
print_r ($company);
print_r ($item);
print_r ($quantity);
}
//echo "<br><font color=\"green\"><b>Invoice added</b></font>";
?>
You might notice in the form that the first entry is not javascript. This does indeed post, just not any additional line items generated from the javascript function.
Thanks for any help.
As I had said in the comments, it seems having divs for display formatting purposes has a negative effect when used within forms utilizing javascript.