Some Assistance On Reply To Comments PHP - php

Could someone give me some assistance on adding reply to my commenting system.
I'm creating a project on Smarty 3 and so far i have done the comments part but i'm having a bit of trouble with the reply part because it won't display the replies could someone check my code to see what i am doing wrong or correct it for me please here is my code below.
PHP Functions from movie class
public function GetMovieComments($con, $movie_id) {
$c = array();
$q = mysqli_query($con,"SELECT * FROM `movie_comments`,`user` WHERE `movie_id` = '".$movie_id."' AND `uid` = `user_id`");
if (mysqli_num_rows($q) > 0) {
while ($r = mysqli_fetch_assoc($q)) {
$c[] = $r;
}
return $c;
}
}
public function GetMovieReplies($con, $comment_id) {
$comment_id = mysqli_real_escape_string($con, $comment_id);
$rp = array();
$q = mysqli_query($con,"SELECT * FROM `movie_replies`,`user` WHERE `comment_id` = '".$comment_id."' AND `uid` = `user_id`");
if (mysqli_num_rows($q) > 0) {
while ($r = mysqli_fetch_assoc($q)) {
$rp[] = $r;
}
return $rp;
}
}
Now calling the functions from movie.php
$comments = $movie->GetMovieComments($con, $movie_id);
if (isset($comments)) {
foreach($comments as $comment) {
$comment_id = $comment['cid'];
$replies = $movie->GetMovieReplies($con, $comment_id);
$smarty->assign('replies',$replies);
}
}
$smarty->assign('comments', $comments);
Now in movie.tpl
{if isset($comments)}
{if $comments neq ''}
{foreach from=$comments key=key item=comment}
<div class="media">
<div class="media-body">{$comment.comment}</div>
</div>
{foreach from=$replies key=key item=reply}
<h4>{$reply.reply}</h4>
{/foreach}
{/foreach}
{else}
<h5>No Comments</h5>
{/if}
{/if}
Could someone please help me i have been trying to solve this for hours lol thanks

For not overwriting the variable replies, I'd do something like this:
// Make GetMovieComments return an array with values or simply an array(), so no check needed
$comments = $movie->GetMovieComments($con, $movie_id);
foreach($comments as $key => $comment) {
$replies = $movie->GetMovieReplies($comment['cid']);
$comments[$key]['replies'] = $replies;
}
$smarty->assign('comments', $comments);
Then you can access the {foreach from=$comment.replies key=key item=reply} to use it within the inner foreach. However that was just one thing, there might be more mistakes in the code...
A couple of things I'd do extra with your code:
public function GetMovieComments($movie_id) {
$comments = array();
// Some data validation to avoid SQL Injections
// You might be better with binding parameters if it's not an int
$id = intval($movie_id);
// You use the connection already stored in this object. You should set it in the constructor
$query = mysqli_query($this->con,"SELECT * FROM `movie_comments`,`user` WHERE `movie_id` = '" . $id . "' AND `uid` = `user_id`");
// No need for the if. This will only enter if there's any result anyway
while ($result = mysqli_fetch_assoc($query)) {
$comments[] = $result;
}
return $comments;
}
// Apply some similar changes to GetMovieReplies() as the ones above.

Related

Recursive function for comment and reply PHP application

I am having difficulty conceptualizing a recursive function for appending replies to comments, replies to replies, replies to replies to replies, etc.
This is my comments table:
Which SHOULD look something like this when rendered:
As it stands I can render each comment associated with the article_id (excluding those that are NOT NULL, of course):
$comments = $commentClass->fetch_article_comments($article_id);
foreach($comments as $comment) {
$comment_id = $comment['comment_id'];
$member_id = $comment['member_id'];
$comment_text = $comment['comment_text'];
$comment_timestamp = timeAgo($comment['comment_timestamp']); //get time ago
//render comment using above variables
}
Now I'm assuming I need to add a recursive function at the end of the above foreach statement, but I have yet to come up with anything remotely successful in appending the comments replies and the replies to each reply.
Can anyone help me accomplish this or perhaps point me in the right direction. I am not entirely familiar with recursive functions. I have done some scanning of the internet and on stackoverflow looking for something that helps, but haven't found anything helpful yet.
I did come across this post which recommended using a hierarchical database system, but I think I would prefer to use a php recursive function for this.
Thanks.
edit
By using the below answers I am only returning the results first comment and then it iterates and displays that one comment indefinitely. I can't figure out why?
My php:
function display_comments($article_id, $parent_id=0, $level=0) {
global $comment;
global $member;
global $signed_in;
global $username;
$comments = $comment->fetch_article_comments($article_id, $parent_id);
foreach($comments as $data) {
$comment_id = $data['comment_id'];
$c_member_id = $data['member_id'];
$comment_text = $data['comment_text'];
$comment_timestamp = timeAgo($data['comment_timestamp']); //get time ago
$member_data = $member->fetch_member_data($c_member_id);
$c_member_username = $member_data['member_username'];
$c_member_avatar = $member_data['member_avatar'];
//render HTML here
$parent = $data['comment_parent'];
display_comments($article_id, $parent, $level+1);
}//end foreach
}//end display_comments()
and my PDO query:
public function fetch_article_comments($article_id, $parent_id) { //$page = (int)(!isset($_GET['page'])) ? 0 : $_GET['page'];
if ($parent_id > 0) {
$parent_id = "= $parent_id";
} else {
$parent_id = "IS NULL";
}
$query = $this->db->prepare("SELECT * FROM `comments2` WHERE `article_id` = $article_id AND `comment_parent` $parent_id ORDER BY `comment_timestamp` DESC");
try{
$query->execute();
$comments = $query->fetchAll(); //returns an array
$query->closeCursor();
return $comments;
} catch(PDOException $e){
die($e->getMessage());
}
}
The core of the problem is this:
$comments = $commentClass->fetch_article_comments($article_id);
I assume, this function somwhere creates and runs SQL, that is similar to SELECT ... WHERE comments.article_id=$article_id. This is not sufficient - you need something like
$comments = $commentClass->fetch_article_comments($article_id, $parent_id);
that translates into SQL similar to SELECT ... WHERE comments.article_id=$article_id AND comments.comment_parent ($parent_id>0)?"=$parent_id":"IS NULL"
Now you can write your PHP function:
function display_comments ($article_id, $parent_id=0, $level=0) {
$comments = $commentClass->fetch_article_comments($article_id, $parent_id);
foreach($comments as $comment) {
$comment_id = $comment['comment_id'];
$member_id = $comment['member_id'];
$comment_text = $comment['comment_text'];
$comment_timestamp = timeAgo($comment['comment_timestamp']); //get time ago
//render comment using above variables
//Use $level to render the intendation level
//Recurse
display_comments ($article_id, $comment_id, $level+1);
}
}
And finally call it with display_comments ($article_id);
You could do something like:
function getCommentsForParent($parent="") {
echo "<div class=\"comment\">";
$db = get("select your db logics where parent = $parent");
foreach ($db as $comment) {
echo "print your comment in a box and make a div around the hole comments"
getCommentsForParent($comment['parent_id']);
}
echo "</div>";
}
invoke function with getCommentsForParent()
With your code it should be something like:
function getCommentForParent($parent="") {
global $commentsClass, $article_id;
$comments = $commentClass->fetch_article_comments($article_id,$parent);
foreach($comments as $comment) {
$comment_id = $comment['comment_id'];
$member_id = $comment['member_id'];
$comment_text = $comment['comment_text'];
$comment_timestamp = timeAgo($comment['comment_timestamp']); //get time ago
getCommentForParent($comment['parent']);
}
}
Look closely, ive adjusted your fetch article_comments. It now has a listener for $parent. Make sure that when your $parent = "", the class will only select the comments with empty parent.
invoke with getCommentsForParent()
It will automatically loop through the parent. Ofcourse this is highly conceptual but given your code you should get the hang of it.

Display data from the database means php smarty mysql

help me understand: There is a table in the database:
id f_gdpec w_gdpec url_gdpec p_gdspec
1 Москва Красноярск www.test.ru 450
2 Москва Красноярск www.test.ru 900
3 Москва Красноярск www.test.ru 600
Need to pull data from a database and display means php means smarty. that's what I did: module.php:
<?php
function mod_gdspec($module_id){
$inCore = cmsCore::getInstance();
$inDB = cmsDatabase::getInstance();
$cfg = $inCore->loadModuleConfig($module_id);
$sql = "SELECT f_gdpec,
w_gdpec,
url_gdpec,
p_gdspec
FROM cms_gdspec";
$result = $inDB->query($sql) ;
if ($inDB->num_rows($result)){
$items = array();
while ($item=$inDB->fetch_assoc($result)){
$items[]=$item;
}
}
$smarty = $inCore->initSmarty('modules', 'mod_gdspec.tpl');
$smarty->assign('items', $items);
$smarty->display('mod_gdspec.tpl');
return true;
}
?>
The template mod_gdspec.tpl:
{foreach item=item from=$items}
<div class="mod_latest_entry">
<div class="mod_latest_f_gdpec">
{$item.f_gdpec}
</div>
<div class="mod_latest_w_gdpec" >
{$item.w_gdpec}
</div>
</div>
{/foreach}
data from tabditsy not appear, I can not understand how much.
ask your might. Thank you for your attention.
corrected script - module.php!!!!!!!!!!!!!
You are returning the value before assigning the value, remove that unnecessary return value
<?php
function mod_gdspec($module_id){
$inCore = cmsCore::getInstance();
$inDB = cmsDatabase::getInstance();
$cfg = $inCore->loadModuleConfig($module_id);
$sql = "SELECT f_gdpec,
w_gdpec,
url_gdpec,
p_gdspec
FROM cms_gdspec";
$result = $inDB->query($sql) ;
if ($inDB->num_rows($result)){
$items = array();
while ($item=$inDB->fetch_assoc($result)){
$items[]=$item;
}
}
// return true;------------>remove this
$smarty = $inCore->initSmarty('modules', 'mod_gdspec.tpl');
$smarty->assign('items', $items);
$smarty->display('mod_tags.tpl');
return true;
}
?>

function returning only once, why?

During my coding I really got stuck into this problem.
I ran a foreach loop and for every item I had to get a certain value from a function.
But I got only one returned. I could not figure out what was happening. I hope you guys surely will.
Below is the short version of my program.
Database structure is given at last.
<?php
function opendb() {
mysql_connect("localhost", "root", "root");
mysql_select_db("something_db");
}
function sql_query($sql) {
$datas = array();
if ($res = mysql_query($sql)) {
$x = 0;
while ( $data = mysql_fetch_assoc($res) ) {
$datas[$x] = $data;
$x += 1;
}
}
return $datas;
}
function get_parent_id($table, $parent, $cid) {
// cid=>child id
$sql = "SELECT * FROM $table WHERE id=$cid";
$datas = sql_query($sql);
$pid = $datas[0]['parent'];
$p_id = $datas[0]['id'];
if ($pid != 0) {
get_parent_id($table, $parent, $pid);
} else {
return $p_id;
}
}
opendb();
$datas_pkg = sql_query("SELECT * FROM tbl_packages WHERE 1");
foreach ( $datas_pkg as $data_pkg ) {
echo $data_pkg['destination_id'] . '-->';
echo $parent_id = get_parent_id('tbl_destinations', 'parent', $data_pkg['destination_id']);
echo '<br/>';
}
?>
Database structure..
tbl_destinations
+--------+-------------------------+-----------+
| id(int)|destination_name(Varchar)|parent(int)|
+--------+-------------------------+-----------+
tbl_packages
+-------+---------------------+-------------------+
|id(int)|package_name(varchar)|destination_id(int)|
+-------+---------------------+-------------------+
If I did not clear my question please let me know so that I can help you to help me.
if($pid!=0)
{
get_parent_id($table,$parent,$pid);
}
You call the function, but never use its value.

Invalid Argument Error Making Search Bar

I'm making a search bar for a site it works in one page but the other one I keep getting invalid argument error. Hopefully everything that is needed is below. I am using codeigniter. Please help. Thanks.
//Doesnt Work//
private function getUsers () {
$search = $this->input->post('search');
if($search && filter_var($search, FILTER_VALIDATE_EMAIL)) {
$where = 'WHERE source_adusers.ad_Email="'.$search.'"';
} else if ($search) {
$where = "WHERE source_adusers.ad_account='".$search."'";
} else if (!$search) {
$where = '';
}
$query = $this->db->query('SELECT *, COUNT(rollout_systems.EAM_USER) as systems FROM source_adusers
LEFT JOIN rollout_systems ON rollout_systems.EAM_User = source_adusers.ad_account '.$where.' GROUP BY source_adusers.ad_account LIMIT 0,50');
$users = null;
foreach ($query->result() as $row) {
$data['account'] = $row->ad_account;
$data['email'] = $row->ad_Email;
$data['name'] = $row->ad_DispName;
$data['systems'] = $row->systems;
$users[] = $data;
}
if(isset($this->data['users'])) {
$this->data['users'] = $users;
} else {
$this->data['users'] = $users;
}
}
//Does Work//
private function getSystems () {
$search = $this->input->post('search');
if ($search) {
$where = 'WHERE disc_systempool.ad_name="'.$search.'"';
} else {
$where = '';
}
$query = $this->db->query('SELECT *, COUNT(rollout_systems.sys_name) as scopes FROM disc_systempool LEFT JOIN rollout_systems
ON rollout_systems.sys_name=disc_systempool.ad_name '.$where.' GROUP BY disc_systempool.ad_name LIMIT 0,50');
foreach ($query->result() as $row) {
$data['model'] = $row->eam_Model;
$data['account'] = $row->ad_name;
$data['city'] = $row->eam_City;
$data['scopes'] = $row->scopes;
$data['search'] = $this->input->post('search');
$systems[] = $data;
}
if(isset($this->data['systems'])) {
$this->data['systems'] = $systems;
} else {
$this->data['systems'] = $systems;
}
}
//Where I'm getting the error//
<tbody>
<? foreach ($users as $user) { ?> <---- Line 18
<tr>
<td class="center"><?=$user['account']?></td>
<td><?=$user['name']?></td>
<td><?=$user['email']?></td>
<td class="center"><?=$user['systems']?></td>
<td class="center">View Details</td>
</tr>
<? } ?>
</tbody>
//Error//
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: headquarters/users.php
Line Number: 18
It shows the right thing. I fixed the problem. I misunderstood what the guy that hired me asked me to do. He said search account name. I was search display name which kept giving me the error.
Try making a var_dump($data); inside your view. If empty. Do the same in your controller by just printing it out. If you see data inside the $data array. Make sure that you are sending the $data array with you into the view $this->load->view("view",$data);
Besides that, i might be wondering why you do foreach on your rows inside of the controller instead of just using the object right in your view
return $query->result();
in view
foreach($users as $user) { print $user->account; }
Hope you figure it out.
Best regards
Jonas

Printing the Categories and Sub Categories Alone

function build_list($id=0,$collapsed="") //return an array with the categories ordered by position
{
$RootPos = "";
$this->c_list = array();
if($id != 0){
$this_category = $this->fetch($id);
$positions = explode(">",$this_category['position']);
$RootPos = $positions[0];
}
// lets fetch the root categories
$sql = "SELECT *
FROM ".$this->table_name."
WHERE position RLIKE '^([0-9]+>){1,1}$' AND c_group = '".$this->Group."'
ORDER BY c_name";
$res = mysql_query($sql) or die(trigger_error("<br><storng><u>MySQL Error:</u></strong><br>".mysql_error()."<br><br><storng><u>Query Used:</u></strong><br>".$sql."<br><br><storng><u>Info:</u></strong><br>",E_USER_ERROR));
while($root = mysql_fetch_array($res)){
$root["prefix"] = $this->get_prefix($root['position']);
$this->c_list[$root['id']] = $root;
if($RootPos == $root['id'] AND $id != 0 AND $collapsed != ""){
$this->list_by_id($id);
continue;
}else{
// lets check if there is sub-categories
if($collapsed == "" AND $id==0){
$has_children = $this->has_children($root['position']);
if($has_children == TRUE) $this->get_children($root['position'],0);
}}}
return $this->c_list;
}
// He is the Author of the code...
Categories Class
Author: Shadi Ali
Now I want to just return the Categories and Sub Categories from the above code.
function browse() {
$categories = new categories;
$categories_list = $categories->build_list();
foreach($categories_list as $c)
{
return $c->$id;
}
}
The above code is not working.... can anyone help me out.
Here are two problems with the browse() function:
The return statement is inside the foreach loop. The statement will return one value for one of the items in the $categories-list (at most), and not continue to loop over the rest of the $categories-list.
The $id variable is never declared or initialised in return $c->$id, perhaps you meant to use $c['id'] or $c->id

Categories