Jump to content

TechnoDiver

Members
  • Posts

    203
  • Joined

  • Last visited

Everything posted by TechnoDiver

  1. Hi Freaks, I've been working on an issue trying to get an infinite scrolling system to work. I originally posted about it here -> I've been trying to debug and figure out the issue as I was pretty sure it was in the jquery/ajax script and not my PHP. The original script I'm using is in the original post linked above bur for reader convenience I'll post it again here -> <script> var userLoggedIn = '<?php echo $user->data()->username; ?>'; $(document).ready(function() { $('#loading').show(); //ajax for loading first posts $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=1&userLoggedIn=" + userLoggedIn, cache: false, success: function(data) { $('#loading').hide(); $('.posts_area').html(data); } }); $(window).scroll(function() { var height = $('.posts_area').height(); //div containing posts var scroll_top = $(this).scrollTop(); var page = $('.posts_area').find('.nextPage').val(); var noMorePosts = $('.posts_area').find('.noMorePosts').val(); if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { $('#loading').show(); var ajaxReq = $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=" + page + "&userLoggedIn=" + userLoggedIn, cache: false, success: function(response) { $('.posts_area').find('.nextPage').remove(); //removes current next page $('.posts_area').find('.noMorePosts').remove(); //removes current next page $('#loading').hide(); $('.posts_area').append(response); } }); } // end if return false; }); }); </script> the issue that I found is in the if statement condition-> if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { I added some console logs-> .... console.log("This is the scrollHeight: " + document.body.scrollHeight); console.log("This is the scrollTop: " + document.body.scrollTop); console.log(""); console.log("This is scrollTop + innerHeight: " + (document.body.scrollTop + window.innerHeight)); console.log(""); if((document.body.scrollTop + window.innerHeight >= 2500) && noMorePosts == 'false') { $('#loading').show(); console.log('This is fucked up'); // noMorePosts = true; ....... And it turns out that the overflow comments were being displayed but I had to scroll alll the way to the bottom of the page for it to happen. In the above code you can see where I altered the if condition to get the overflow comments to display sooner. This seems like a really bad fix to me as it's such an absolute value (2500) and doesn't take into account so many different variables in user system, setup etc etc. Also, at times it will load the overflow comments more than once. I've seen them repeated up to 3-4 times, which is certainly not acceptable. So I have 2 questions about this issue that I'm really hoping someone can help me resolve: 1) What is a more appropriate fix for the if condition rather than having that hardcoded 2500 in there? 2) What are some ways I can fix the sometimes repetitive overflow comments displaying? As I said in my original post, this jquery/ajax isn't my code and I'm trying to work through it when I get the time, but there is no mechanism in it to make noMorePosts = true and my commented out attempt at it didn't work. To say that I'm really uncomfortable with jquery and ajax would be an understatement. I look forward to reading your responses and hope a great weekend to you all. TIA
  2. Ok, I understand exactly what you're saying and I thought I addressed this with starting $count = 1. That way after the loop runs 10 times ($limit) than $count = 11 and is therefore > $limit. This is why I'm really lost on it. Even after displaying the first 10 posts it's actually not adding the else string to the end -> $str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align: centre;'> No more posts to show!</p>"; because I'm not seeing 'No more posts to show!' as I do if I change the '>' operator to '<' or '=' or '<=' in the same if statement, for example. So I don't really know where to go from here. I feel my PHP is, at least logically sound, though I know I'm no great coder, and I keep getting my head stuck on the Ajax. Which isn't my code, as I stated before, but I've been studying it and outside the 2 seemingly useless variables height and scroll_top it seems to my very untrained eye it should do something lol. Have I missed something in my PHP logic? I've looked at it 100,000 times
  3. Thanks for taking the time on that response, kicken, it gave me a lot to think about and I managed to get the posts displayed, so at least part of the ajax script is working, but it only displays the top 10 ($limit) and the infinite scroll part of it still isn't working. I've been reading articles, watching videos and staring at it on and off for hours trying to familiarize myself with what the jquery/ajax is actually doing, still have figured it out. Everything in the dev tools seems as it should be. I get the 200 response for the ajax_load file and it helped me fix my mistake that stopped any posts from loading to where I am now - first ten posts load, none of the others do when scrolling. The URL doesn't even change, which I assume it would after hit the scroll point that loads the posts, from the looks of the code. If you have any other suggestions I'm open to hearing anything on the matter. I feel like a baby in the woods trying to get this jquery working Yea, you've given me a whole new dimension to consider. Total noob mistake not seeing that that would be a problem. I'm going to keep it like is for now, only because the project isn't live and I'm also feeling completely overwhelmed by this particular task in the project and I feel that when I get the infinite scroll working properly I can use it as an anchor point while I mess with all the things wrong that I'll need to correct
  4. No, that's not alright with me actually, I'm just experienced enough to have foreseen it, I'm still trying to get my head around this AJAX. Was doing that as the notification for this comment popped-up actually. I'm certainly glad you pointed it out though. What would you suggest??
  5. So this is kind of a carry on from my last post about while looping, but I felt it was better to start it in a new thread because the framing of the question has changed. For those of you who responded to my last post I thank you and here is the issue and backstory on that post: I'm trying to integrate an AJAX infinite scrolling system into a project. I'm really uncomfortable with AJAX and have watched a few tutorials on it and have tried to integrate what I've learned into my PHP. The one tutorial that made the most sense to me also, obviously uses some PHP but it's kept at a basic level and the PHP of my own that I'm integrating it with is quite a bit more in depth. Before I start with the breakdown, I'd like to make clear that I'm not ignoring anyone's advice on using a foreach over the while loop. The ajax guy is using a while loop in his more simple examples and since I'm so uncomfortable with AJAX I wanted to stay as true to his examples as possible until I got it functioning correctly then I plan on tidying it up. I just want to get it functioning first to where I have a deeper understanding as I'm doing a lot of customization so it fits with my already written code. That being said, I'm going to try to make this post as organized and clear as possible as I really need some help. I have a news_feed.php includes file that looks like this-> <div class="col-sm-12 col-lg-8 ms-3 me-3 column2"> <form action="" method="POST"> <textarea class="form-control" name="post_text" id="text-area" placeholder="Post to your profile" rows="6" autofocus></textarea> <div class="buttons"> <input class="form-group btn btn-outline my-2 button" type="submit" name="submit_post" id="post-button" data-bs-toggle="tooltip" title="Post to your profile" data-bs-html="true" value="Post"> </div> </form> <?php //$post->getUserPosts(); ?> <div class="posts_area"></div> <img src="img/icons/loading.gif" id="loading"> </div> <!-- end newsfeed --> </div> <!-- end inner row --> </div> </div> It's all pretty straight forward. When the $post->getUserPosts() is uncommented all the posts are displayed. It's commented out right now because of the next 2 files. Next I have an ajax_load_posts.php file that looks like this -> <?php require_once($_SERVER["DOCUMENT_ROOT"] . "/qcic/assets/core/init.php"); $user = new User(); $posts = new Post(); $limit = 10; // loaded posts per call // pull userLoggedIn from ajax script $request = $_REQUEST['userLoggedIn']; $posts->getUserPosts($request, $limit); The last line in this file is why I have the $post->getUserPosts() in the previous one commented out. Next I have the following AJAX. None of this is my code and it's the code I'm trying to integrate into my own project -> <script> var userLoggedIn = '<?php echo $user->data()->username; ?>'; $(document).ready(function() { $('#loading').show(); //ajax for loading first posts $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=1&userLoggedIn=" + userLoggedIn, cache: false, success: function(data) { $('#loading').hide(); $('.posts_area').html(data); } }); $(window).scroll(function() { var height = $('.posts_area').height(); //div containing posts var scroll_top = $(this).scrollTop(); var page = $('.posts_area').find('.nextPage').val(); var noMorePosts = $('.posts_area').find('.noMorePosts').val(); if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { $('#loading').show(); var ajaxReq = $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=" + page + "&userLoggedIn=" + userLoggedIn, cache: false, success: function(response) { $('.posts_area').find('.nextPage').remove(); //removes current next page $('.posts_area').find('.noMorePosts').remove(); //removes current next page $('#loading').hide(); $('.posts_area').append(response); } }); } // end if return false; }); }); </script> Finally I have my getUserPosts() method in my Post class. The majority of this is my code but I've had to make some amendments for this particular task I'm working on. (again, please don't think I'm ignoring anyones advice, I'm not, I will change many things once my understanding is more complete and I get it functioning). -> <?php public function getUserPosts($data, $limit) { // public function getUserPosts() { //$page comes from the $_GET data in ajax script $page = $data['page']; $userLoggedIn = $this->user->username; if($page == 1) { $start = 0; } else { $start = ($page - 1) * $limit; } $table = "un_posts"; $field = "deleted"; $value = "no"; $rule = "ORDER BY id DESC"; $query = $this->_db->get($table, array($field, "=", $value), $rule); $this->_data = $query->all(); // $this->_data is an array of objects $str = ""; //html string to return if (count($this->_data) > 0) { $num_iterations = 0; # number of results checked (not necessarily posted) $count = 1; // foreach ($this->data() as $obj) { // $post_data = array( // "id" => $obj->id, // "content" => $obj->content, // "added_by" => $obj->add_by, // "date_added" => date("F d, Y H:i:s", strtotime($obj->date_added)), // "user_to" => $obj->user_to, // ); $cnt = 0; while($cnt < count($this->data())) { $post_data = array( "id" => $this->data()[$cnt]->id, "content" => $this->data()[$cnt]->content, "added_by" => $this->data()[$cnt]->add_by, "date_added" => date("F d, Y H:i:s", strtotime($this->data()[$cnt]->date_added)), "user_to" => $this->data()[$cnt]->user_to, ); //prepare user string if it's not posted to a user if ($post_data["user_to"] == "none") { $user_to = ""; } else { $user_to_obj = new User($post_data["user_to"]); $user_to_firstname = $user_to_obj->data()->firstname; $user_to_lastname = $user_to_obj->data()->lastname; $user_to = "to <a href='" . $post_data["user_to"] ."'>" . $user_to_firstname . " " . $user_to_lastname . "</a>"; } //check if poster has account closed $added_by_obj = new User($post_data["added_by"]); if ($added_by_obj->isClosed()) { continue; } if($num_iterations++ < $start) { continue; } //load 10 posts and break if($count > $limit) { break; } else { $count++; } //TODO change this for people who use username instead of real names $firstname = $added_by_obj->data()->firstname; $lastname = $added_by_obj->data()->lastname; if ($firstname && $lastname) { $name = $firstname . " " . $lastname; } else { $name = $added_by_obj->data()->username; } $profile_pic = $added_by_obj->data()->profile_pic; //timeframe $datetime_now = date("Y-m-d H:i:s"); $start_date = new DateTime($post_data["date_added"]); //time of post $end_date = new DateTime($datetime_now); // current time $interval = $start_date->diff($end_date); //difference if ($interval->y >= 1) { if ($interval == 1) { $time_message = "1 year ago"; } else { $time_message = $interval->y . " years ago"; } } elseif ($interval->m >= 1) { if ($interval->d == 0) { $days = " ago"; } elseif ($interval->d == 1) { $days = "1 day ago"; } else { $days = $interval->d . " days ago"; } if ($interval->m == 1) { $time_message = "1 month " . $days; } else { $time_message = $interval->m . " months " . $days; } } elseif ($interval->d >= 1) { if ($interval->d == 1) { $time_message = "Yesterday"; } else { $time_message = $interval->d . " days ago"; } } elseif ($interval->h >= 1) { if ($interval->h == 1) { $time_message = "An hour ago"; } else { $time_message = $interval->h . " hours ago"; } } elseif ($interval->i >= 1) { if ($interval->i == 1) { $time_message = "A minute ago"; } else { $time_message = $interval->i . " minutes ago"; } } elseif ($interval->s < 30) { if ($interval->s == 1) { $time_message = "Just now"; } else { $time_message = $interval->s . " seconds ago"; } } $str .= " <div class='status_post'> <div class='post_profile_pic'> <img src='../usernet/img/profile_pics/{$profile_pic}' width='50'> </div> <div class='posted_by'> <a href='{$post_data['added_by']}'> {$name} </a> {$user_to} &nbsp;&nbsp;&nbsp;&nbsp; {$time_message} </div> <div id='post_body'> {$post_data['content']} <br> </div> </div> <hr>"; $cnt++; } if($count > $limit) { //keeping these hidden just to store the values $str .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'> <input type='hidden' class='noMorePosts' value='false'>"; } else { $str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align: centre;'> No more posts to show!</p>"; } } echo $str; } The original commented out at the top (with no parameters) is my original and corresponds to the commented out call to this method in the first file I posted. As is, this is not showing the posts only the loading.gif from the first file. I suspect it's not reading the ajax_load_post.php file correctly if at all, as that is where the new call to this method is located. I'm not sure what my actual question is other than "How do I get this working properly?". outside using AJAX for some API calls this is my first foray into using it in a more complex manner. I've tried to keep my code well commented and this post organized so as not to discourage people from responding. I'm pretty lost in the jungle right now and any compass or map any of you could provide would be appreciated. Thank you.
  6. OK, thank you all for your responses. I'm not done with this issue yet but it seems more appropriate to continue it in a new thread, which is what I'll do
  7. Ok, thanks all. I didn't realize that the false return was built into the mysqli function. I guess I thought that breaking at the end was automatic by the while loop functionality. Knowing that, it's an easy fix -> <?php $cnt = 0; while($cnt < count($this->data())) { $post_data = array( "id" => $this->data()[$cnt]->id, "content" => $this->data()[$cnt]->content, "added_by" => $this->data()[$cnt]->add_by, "date_added" => date("F d, 20y H:i:s", strtotime($this->data()[$cnt]->date_added)), "user_to" => $this->data()[$cnt]->user_to, ); Not a problem, but I had a few if statements within the loop that seemed would work best if I could use 'break' and 'continue' if certain conditions weren't met, which I couldn't with the foreach() $this->_data is a private attribute of the class. I have a separate public function data() that returns $this->_data. All's good now though, my misunderstanding was in the functionality of the mysqli function and the while loop function. You folks explained it perfectly, thanks to you all
  8. Hi, Freaks, I hope all are well. I'm trying to make a while loop and there's a common manner used that I've seen in many, many example of code -> <?php while($row = mysqli_fetch_array($data_query)) { ... } and this manner of doing it auto-stops when it's to the end of the mysqli array. Using this exact way is not compatible with the syntax that I can use as I use a database wrapper that is highly abstracted. for example, this would be the typical layout of a DB query for a user post -> <?php $table = "un_posts"; $field = "deleted"; $value = "no"; $rule = "ORDER BY id DESC"; $query = $this->_db->get($table, array($field, "=", $value), $rule); $this->_data = $query->all(); // $this->_data is an array of objects and this would be my typical way of assigning the data -> <?php foreach ($this->data() as $obj) { $post_data = array( "id" => $obj->id, "content" => $obj->content, "added_by" => $obj->add_by, "date_added" => date("F d, Y H:i:s", strtotime($obj->date_added)), "user_to" => $obj->user_to, ); for project specific reasons I'd like to change this from a foreach loop to a while loop. What I found out is that the auto-stop of the while loop using the $row = mysqli..... does not work if I do something like this -> <?php while($obj = $this->data()) { $post_data = array( "id" => $obj->id, "content" => $obj->content, "added_by" => $obj->add_by, "date_added" => date("F d, 20y H:i:s", strtotime($obj->date_added)), "user_to" => $obj->user_to, ); and it creates an infinite loop. Keeping in mind that $this->data() (I have a class method data() that returns $this->_data if anyone noticed the difference) is an array of objects why am I not getting the same result as <?php while($row = mysqli_fetch_array($data_query)) { ... } I don't understand. They're both arrays being looped through. What's the difference where mine isn't breaking the loop at the end but the mysqli array breaks the loop at the end of it?
  9. Another edit: EDIT: I've tried to do this statically and assign $profile_pic at the top of the registration.php page and I get the empty array error still. I've also taken it out of the User class and placed it as a function at the top of the registration.php page and I'm still getting the empty array error. -> <?php require_once($_SERVER["DOCUMENT_ROOT"] . "/qcic/assets/core/init.php"); $html = ""; $errors = array(); $sent = false; $js_switch = true; function assignDefaultProfilePic() { $path = "img/profile_pics/defaults/"; $files = glob($path . '*.png'); $file = array_rand($files); $f = explode('profile_pics/', $files[$file]); $profile_pic = end($f); return $profile_pic; // echo $profile_pic; } // $profile_pic = User::assignDefaultProfilePic(); and -> <?php if($validation->passed()) { $user = new User(); // $profile_pic = $user->assignDefaultProfilePic(); try { $user->create(array( "username" => Input::get("username"), "password" => Hash::make(Input::get("password")), "email" => Input::get("email"), // default profile pic functionality goes here // "profile_pic" => $profile_pic, "profile_pic" => assignDefaultProfilePic(), // "profile_pic" => $profile_pic, "group" => 2, )); I don't understand why it only works (gets the array) while logged in as an already registered user. I can't even think of anything else to try. Looking forward to your responses
  10. I couldn't edit my last post, thankfully I copied it before clicking the button: EDIT: Ok, so I was testing some things. This is in the registration form a I've edited my code slightly. And I'm trying to get it to assign the path string to the DB upon registration, but it keeps coming back as empty array when the 'register' button is clicked. which means it's happening at the array_rand() function, but if I sign in as a registered user and echo it out it prints the string. I don't understand why it's doing this. here is my edited code -> <?php public function assignDefaultProfilePic() { $path = "img/profile_pics/defaults/"; $files = glob($path . '*.png'); $file = array_rand($files); $f = explode('profile_pics/', $files[$file]); $profile_pic = end($f); return $profile_pic; // echo $profile_pic; } and here is the code at the top of my registration page about halfway down in the validation->passed if statement is where I'm building the registration array where I need to profile_pic info-> <?php require_once($_SERVER["DOCUMENT_ROOT"] . "/qcic/assets/core/init.php"); $html = ""; $errors = array(); $sent = false; $js_switch = true; // var_dump(Token::check(Input::get('token'))); if(Input::exists()) { if(Input::get("register_button")) { if(Token::check(Input::get('token'))) { $validate = new Validate(); //create requirements $validation = $validate->check($_POST, array( "username" => array( "name" => "Username", "required" => true, "min" => 2, "max" => 20, "unique" => "users" //unique to the users table ), "email" => array( "name" => "Email", "required" => true, //have to validate email, think I'll make it a public static function //"valid_email" => false ), "email2" => array( "name" => "Confirmation email", "required" => true, "matches" => "email" ), "password" => array( "name" => "Password", "required" => true, "min" => 6, ), "password2" => array( "name" => "Confirmation password", "required" => true, "matches" => "password" ) )); if($validation->passed()) { $user = new User(); // $profile_pic = $user->assignDefaultProfilePic(); try { $user->create(array( "username" => Input::get("username"), "password" => Hash::make(Input::get("password")), "email" => Input::get("email"), // default profile pic functionality goes here // "profile_pic" => $profile_pic, "profile_pic" => $user->assignDefaultProfilePic(), "group" => 2, )); $sent = true; $js_switch = true; } catch(Exception $e) { die($e->getMessage()); } } else { $errors = $validation->errors(); } } } elseif(Input::get("login_button")) { require("login.php"); } } ?> Any insight on this would be really appreciated
  11. Hi, Freaks I have this function -> <?php public function assignDefaultProfilePic() { $path = "img/profile_pics/defaults/"; $files = glob($path . '*.png'); $file = array_rand($files); return $files[$file]; // print_r($files); } and it's the weirdest thing. If I uncomment the print_r() and leave only $path and $files it prints the array of directory contents and everything seems fine. When I use it as is I get the following error-> I don't understand how it's possible, I've changed nothing else. Can someone please explain this to me?!
  12. Do you have a limited number of replies per initial comment or is it able to take an infinite amount (think like Reddit)??
  13. Hi, Psycho, I've finally gotten some smaller issues out of the way so I can start on this again. I was looking through you response and it pretty much makes sense to me except the third item (reply_id) I'm picturing comment_id as the primary key but I don't understand exactly what you're saying with the reply_id. How could it be empty or 0? If you get the time and will do you mind going into a bit more detail on this?! Thanks, I'd love to read whatever else you'd have to say about it.
  14. Haha, this is the first place that I placed the redirect and got that error message. After the error the wind completely left my sails because I couldn't figure out where else it should have gone and if it didn't go here then it called into question everything I thought I understood. Seeing it was my naive syntax error with the link string and that it works now where I had originally put the redirect gave me back some confidence. re-placing the message = True isn't a big deal. Thank you for you response
  15. Hay kicken, I've finally been able to get back to my project. I had to refresh my brain on the issues to solve the last few days and I figured a good way to do this was to return to the responses here. I'm not really clear on exactly what you mean in the line I quoted you in. If you find the time and the will would you mind breaking it down into what exactly is happening behind the scenes regarding this?! I think you mean that the previously existing data is being loaded before the new data (in this case the comment) is being inserted. But I feel, well I'm not sure how I feel, and if what I think you mean is correct then I'm not sure why it's doing that. From my perspective the very last command in the top of the display page is the one that changes $message to True, and that is functional as after 'submit' is clicked the message is shown, just not the comment or the count. I'm also not clear on where to put the redirect or exactly how to implement it. My redirect looks like this -> <?php Redirect::to("single_post.php?post_id=<?php echo $post_id; ?>&related=<?php echo $related; ?>"); I thought it should go within this if statement at the top of the display page <?php //simply increase #views per page load if($post_id && !empty($post_id)) { $post->viewCount($post_id); //comment to db if(Input::get('submit')) { // mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); if($comment->add($post_id, Input::get('comment'))) { $message = true; } } } And tried it after the statement outside of it. In all cases I've received this gut-wrenching error that I can't make sense of within the context of the redirect. I can't see why a redirect using the same URL that gets one to this page is causing this chaotic error message. So if you get the time and/or will to go into a bit more detail on this (or anyone reading this) I'd really love to read it, Thanks and have a great weekend
  16. Ok, I get this. There's been times that I've had to reload multiple time (f5) when messing with an issue and it's duplicated the comment. So this is interesting. I'm going to read that article and give it a go. Thank you, I may have to come back and readdress this but hopefully I can get this working on my own. Have a great weekend
  17. OK. It wasn't immediately obvious what you meant at first, after a cup of tea and some contemplation it clarified itself and things are almost working properly. In fact they are working properly except upon 'submit' the page reloads, I get the message 'true' that the comment has been submitted, and it is present in the DB. But it doesn't show the comment nor the updated commented count until I manually reload the page a second time: click 'submit (only change is it says the comment has been submitted and comment goes to DB) -> manually reload page (now the comment count refreshes and the comment is visible). I have no idea why this is happening, any hints?? Here's my amended Comment class -> <?php class Comment { // public static $num_comments; private $_db, $_user, $_data, $_count; private static $_table = "comments"; public function __construct($post_id) { $this->_db = DB::getInstance(); $this->_user = new User(); $rule = "AND comment_status='approved' ORDER BY date_added DESC"; $field = "post_id"; $query = $this->_db->get(self::$_table, array($field, "=", $post_id), $rule); $this->_data = $query->all(); $this->_count = count($this->_data); } public function display() { $cnt = 0; foreach($this->_data as $obj) { $data = array( "id" => $obj->id, "post_id" => $obj->post_id, "commenter" => $obj->username, "comment" => $obj->body, "date" => date("F d, Y H:i:s", strtotime($obj->date_added)), "profile_pic" => $this->_user->profilePic($obj->username), ); echo HTML::comments($data, $cnt); $cnt++; } } public function count() { return $this->_count; } public function add($id, $body) { if(!empty($body)) { $this->_db->insert(self::$_table, array( "post_id" => $id, "username" => $this->_user->data()->username, "body" => $body, )); return true; } } And here's the top of the display page (excuse all the instantiations, they'll be put in a require() eventually, it's just easier for me to see everything at the level I'm at) -> <?php require_once($_SERVER["DOCUMENT_ROOT"] . "/qcic/assets/core/init.php"); $user = new User(); $actors = new Actors(); $category = new Category(); $post = new Post(); $comment = new Comment(Input::get("post_id")); $subs = new Subs(); $post_id = Input::get("post_id"); $related = Input::get("related"); $message = false; //simply increase #views per page load if($post_id && !empty($post_id)) { $post->viewCount($post_id); //comment to db if(Input::get('submit')) { // mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); if($comment->add($post_id, Input::get('comment'))) { $message = true; } } } like I said, upon 'submit' click, comment goes to DB, message goes to 'true' but the comment count and the comment don't update on the initial reload. I have to reload a second time for them to take effect. It's not something I've experienced before.
  18. Yea, yea, I'm really stupid sometimes. I got thinking about what you said again and the more I thought the more sense it made. You're right that's exactly the issue. <div class="comment-area clearfix"> <!-- need to make this dynamic --> <h5 class="title"><?php echo $comment->count(); ?> Comments</h5> <?php if(!$message): ?> <h4>Leave a comment</h4> <?php else: ?> <div class='success'> <p class='bg-color-third text-center text-color-primary'>Your comment has been published</p> </div> <?php endif; ?> <div class="contact-form-area mb-5"> <form action="single_post.php?post_id=<?php echo $post_id; ?>&related=<?php echo $related; ?>" method="POST"> <div class="row"> <div class="col-12"> <textarea name="comment" class="form-control" id="message" placeholder="Comment"></textarea> </div> <div class="form-group"> <input type="submit" name="submit" value="Submit Comment" class="btn bg-color-primary text-color-fourth"> </div> </div> </form> </div> <?php echo $comment->display($post_id); ?> display() is being called after count(). Is the only way to rectify this to put them into different class methods to be called separately?? I tried assigning display() to a variable at the top of the page to be called later, and that had catastrophic consequences. So is there any other way to do this and still keep the $this->count inside the display method or do I need to put it in a method of its own?
  19. There's really not much more to this class right now. display() is executing because the comments are there and the line that's commented as TEST PURPOSES shows the number 2 under the displayed comments. Here is the entire comment class as it stands right now -> <?php class Comment { // public static $num_comments; private $_db, $_data, $_user, $_count; private static $_table = "comments"; public function __construct() { $this->_db = DB::getInstance(); $this->_user = new User(); } public function add($id, $body) { if(!empty($body)) { $this->_db->insert(self::$_table, array( "post_id" => $id, "username" => $this->_user->data()->username, "body" => $body, )); return true; } } public function display($post_id) { $rule = "AND comment_status='approved' ORDER BY date_added DESC"; $field = "post_id"; $query = $this->_db->get(self::$_table, array($field, "=", $post_id), $rule); $this->_data = $query->all(); $this->_count = count($this->_data); $cnt = 0; foreach($this->_data as $obj) { $data = array( "id" => $obj->id, "post_id" => $obj->post_id, "commenter" => $obj->username, "comment" => $obj->body, "date" => date("F d, Y H:i:s", strtotime($obj->date_added)), "profile_pic" => $this->_user->profilePic($obj->username), ); echo HTML::comments($data, $cnt); $cnt++; } echo $this->count(); // JUST HERE FOR TEST PURPOSES } public function count() { return $this->_count; } As you can see I tried to do it statically at one time too and that wasn't getting there either. In the SS you can see at the top it should say '2 Comments' but it only says 'Comments' and at the bottom you can see that it returns '2' from the TEST commented line in the display() method. I'm kind of (really) at a loss, it seems like a simple thing and I've been messing with it for a few hours. It just won't display. As an aside, I did have this working once. That was yesterday I had a dedicated method to query the DB and count the comments for each post; though that wasn't working perfectly because once a comment was added and the page reloaded it didn't up the count until the page reloaded a second time. It wasn't until I was in bed last night that I realized it was redundant because display() would provide that count with only one DB query, so today I went to tighten it up a bit and now I can't get it to display the count in that location at all.
  20. I'm really confused and hoping someone can point me in the right direction. I feel this is one of those really simple things that I'm going to want to slap myself in the head over when it's resolved. It simply involves displaying a comment count in a certain area of my project. I have this method to display comments here -> <?php public function display($post_id) { $rule = "AND comment_status='approved' ORDER BY date_added DESC"; $field = "post_id"; $query = $this->_db->get(self::$_table, array($field, "=", $post_id), $rule); $this->_data = $query->all(); $this->_count = count($this->_data); $cnt = 0; foreach($this->_data as $obj) { $data = array( "id" => $obj->id, "post_id" => $obj->post_id, "commenter" => $obj->username, "comment" => $obj->body, "date" => date("F d, Y H:i:s", strtotime($obj->date_added)), "profile_pic" => $this->_user->profilePic($obj->username), ); echo HTML::comments($data, $cnt); $cnt++; } echo $this->count(); // JUST HERE FOR TEST PURPOSES } public function count() { return $this->_count; } The line that's commented for FOR TEST PURPOSES displays the comment count as expected. The issue arises when I port it to the display page. <h5 class="title"><?php echo $comment->count(); ?> Comments</h5> I get no error, but I get no number for the comment count either. I don't understand why. I've obviously done the instantiation at the top, I didn't overlook that (represented by $comment). As the count stands right now it should say '2 Comments'. The $this->count() test line works, why am I getting no result where it matters?
  21. excellent. I think I'll never have problems with timestamps again after this
  22. Ok, thank you, I didn't know this about either. I will be researching it when the time comes. I wish I could save responses to make them accessible from my profile. I can't remember every single thing I learn on here and there's been at least twice I've been called out on it where responders have replied the same things to me more than once and let me know they had already answered that issue lol anyways, c'est la vie I appreciate the help. I'm not to a point that I need intervals yet so I'm doing it like this, and it's working fine now -> in DB -> type: TIMESTAMP, default: CURRENT_TIMESTAMP PHP -> "date" => date("F d, 20y H:i:s", strtotime($obj->date_added)) Thanks again
  23. OK, I get it. The 2 factors that I used to determine how to store and pull date/times was that I wanted the date/time to be set automatically when content was sent to the DB ( thus using current_timestamp as the default value) and I guess I thought that bigint() would be different than it turned out to be. The other factor is that I needed it in a format that I can do math with so as to calculate time integers etc. I thought having a bigint() type with current_timestamp as default would accomplish this, it doesn't as we both now know ( you already knew, I just learned) I get so tied up in so many different aspects of this project that I just noticed this recently. As I sit back and contemplate the things I'm reading from you and Barand I'm thinking I'll store them as a Timestamp type with current_timestamp as the default and then to do the math when needed I'll convert it to Unix timestamp after retrieval from the DB. Would that be the most efficient way to do this? I was hardcoding in the first 2 digits because without it it just showed '31' ( which I just noticed, until today I was seeing it as '21, which was probably just my oversight) I get pretty overwhelmed with all the new things I have to learn and research for this project and overlook some relatively obvious things often. But I think I now know what I have to do - store them in DB as timestamp type, current_timestamp default and then change them to Unix timestamps when I want/need to do math with them for time interval etc. If either of you gentlemen think there is a better way I'm definitely down to hear about it. Thanks both for the replies
  24. For posts, comments etc in my DB the date_added column is set to bigint() with the current timestamp as default. When retrieving the timestamp from the DB I'm using this formatting -> "date" => date("F d, 20y H:i:s", $obj->date_added) An item that has this timestamp in the DB -> 20211021141214 Is displaying this date/time -> October 06, 2031 14:13:34 I've been doing it this way for awhile and I just noticed that the date is 10 years off even though the time stamp says 2021 at the beginning. What's going on here? P.S. Oddly enough, while typing this a few things to check came to mind. I put everything back to normal and now this timestamp ->20211026114045 is returning this date/time -> DECEMBER 03, 2031 03:34:05 I don't get it. That last one looks to me as it should be Oct. 26, 2021 11:40:45 which is exactly when I posted it on my system clock. I haven't been able to find anything to explain this and I've not manipulated anything programmatically. Only the date() format that I provided above
  25. Of course I understand the difference between them. In the code block where I used == in both the if and elseif statements we're making a comparison. In the assignment blocks we're not making a comparison but assigning a new value to the display attribute. There's 2 comparison statements and 2 assignment statements, I simply asked why == was only needed in one of those comparison statements. What I don't understand is your use of actual value and effective value, nor why you think this is such a stupid question.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.