comment like facebook script - php

I already have an script where it will allow a user whom is logged in to comment on other users. One field for the usercommenting "men_id" and another field for the user being commented on commented_men_id. Well I save it in a comment table and to pull it I make a while I make a select to get the comment of men_id while getting the comment I do another while loop inside the while loop to get the user name and id to return it in the comment. Now the next step is to let other user to comment on top of the comment that is already there. I was wondering if I have to make another table or just create another table to get the comments on another comments. I was also wondering in terms of the php script will I have to create another while loop inside the second while loop to pull the subcomments?
So far I have the next structure
$sql1 = "SELECT id, mem_id, commented_id, comment
FROM comments
WHERE commented_id = '$id'";
while($row=msql_fetch_array($sql)) {
$id_coment = $row['id'];
$mem_id = $row['mem_id'];
$comment = $row['comment'];
$sql_member_data = msql_query("SELECT id, member_name FROM users WHERE id ='$id_coment'");
while($row2=msql_fetchj_array($sql_member_data)) {
$user_id =$row2['id'];
$user_name =$row2['member_name'];
echo '<div>'.$user_name.'</div>';
echo '<div>'.$comment.'</div>';
}
}
I advise might not be the best code but it is posting the comment, Now how can I get a comment within the comment generated by this script.
Thank you guys.

If you truly want a something like Facebook's commenting system, you are going to have to do a lot more than that. I made my own little system and it's nicely styled with some really awesome jQuery effects.
Here's what you are going to need
Section to get all your comments (which you have -- check for syntax errors)
Form and script to post your comments
And you will probally need to use jQuery and AJAX for the commenting and some more jQuery to auto-refresh like facebook does.
That's my take on it. No one else hate on me for this, just trying to give some input on it.
<?php
// Connect to database here
// Search and start loop to get all comments
$sql_comments = mysql_query("SELECT * FROM comments WHERE type='main'");
while($rows_comment=mysql_fetch_array($sql_comments)){
// Get comment information
$main_comment_id = "".$rows_comment['id']."";
$main_comment_mem_id = "".$rows_comment['mem_id']."";
$main_commented_id = "".$rows_comment['commented_id']."";
$main_comment = "".$rows_comment['comment']."";
// Get user information
$sql_member_data = msql_query("SELECT * FROM users WHERE id ='$main_comment_mem_id'");
while($row2=msql_fetchj_array($sql_member_data)) {
$user_id = "".$row2['id']."";
$user_name = "".$row2['member_name']."";
}
// Display comment
echo "<b>$user_name</b><br>$main_comment";
// Search for any sub-comments
$sql_subcomments = "SELECT * FROM comments WHERE sub_commented_id='$main_comment_id' AND type='sub'";
while($row_subcomment=msql_fetchj_array($sql_subcomments)) {
// Get sub comment information
$subcomment_id = "".$row_subcomment['id']."";
$sucomment_mem_id = "".$row_subcomment['mem_id']."";
$subcomment_comment = "".$row_subcomment['comment']."";
// Get sub commenter information
$sql_member_data_sub = msql_query("SELECT * FROM users WHERE id ='$subcomment_mem_id'");
while($row2_sub=msql_fetchj_array($sql_member_data_sub)) {
$user_id_sub = "".$row2_sub['id']."";
$user_name_sub = "".$row2_sub['member_name']."";
}
// Echo sub comment
echo "<div style='margin-left: 20px;'><b>$user_name_sub</b><br>$subcomment_comment</div>";
}
}
?>

Related

What PHP do I need to insert into this mysqli_fetch_array to ensure NULL urls aren't used?

I have a webpage which uses php to pull through data from a MySQL database. The database stores my writing portfolio organised by columns date, url, category, title, publication, description. It pulls through the title and publication and uses the url to turn it into a hyperlink (see code below). So far, so good.
Where I'm stuck: Sometimes there's no url for something I've published (e.g. for a few of the 'Content & Copywriting' items on my site), but it still turns my title and publication into a link: a link to "_blank". When there is a NULL url, I need it to not turn my title into a link at all.
So, I think I need to insert some sort of logic so that if url=NULL, then it doesn't make the text into a link, instead of creating a link to "_blank". But this is completely beyond my capabilities right now - I don't know where to even start !
I hope that all makes sense. Any guidance/pointers in the right direction welcome! And please let me know if anything's not clear.
<?php
$query = mysqli_query($dbconnect, "SELECT * FROM main WHERE category = 'Content & copywriting' ORDER BY date DESC")
or die (mysqli_error($dbconnect));
while ($row = mysqli_fetch_array($query)) {
echo "<a href=$row[url] target='_blank'>$row[publication] - $row[title]</a><br>";
echo "$row[description]<br><br>";
}
?>
try check for empty values
while ($row = mysqli_fetch_array($query)) {
if( !empty( $row['url'])){
echo "<a href=$row[url] target='_blank'>$row[publication] - $row[title]</a><br>";
}
echo "$row[description]<br><br>";
}

Making comment section for a blog based on PHP, MySQL and HTML

I'm struggling for a few days right now with making a comment section for a really simple blog based on PHP, MySQL and HTML. I can add posts, edit them but I have a problem with showing comments. My code shows first post and comment only but rest of the posts without comments. This is the code i should show you I think.
$wyswkom = mysqli_query($polacz, "SELECT * FROM kom");
$komy = mysqli_fetch_assoc($wyswkom);
$wynik = mysqli_query($polacz, "SELECT * FROM news");
while($news = mysqli_fetch_assoc($wynik)){
if($news['id'] == $komy['idnewsa']) {
print $news['autor'].": ".$news['tekst']." / id: ".$news['id']."</br>"."Komentarze: ".$komy['tekst']." -".$komy['autor']."<br>";
} else {
echo $news['autor'].": ".$news['tekst']." / id: ".$news['id']."</br>";
}
}
mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row
as an associative array
Property $wynik always include only first comment from your DB.
Right way how to do this is use WHERE in your SQL statements and load only data you will need. Then iterate over like you are doing for news.
SELECT * FROM kom WHERE idnews = 1
Best way how to learn this would by use some tutorial. This is simple problem with lots of good examples outside.

Logging profile updates in PHP

I have a edit profile page in my social media website.
When users click submit on the form. I run an update query to obviously update the users field in the database.
How can I optimize this scenario to include the logging of which particular fields are updated?
So for e.g.
One scenario could be:
Chris updated his profile picture.
Another scenario would be:
Chris updated his profile, inc:
Email
Username
Address
Address 2
Can anyone offer a solution to this?
I feel there is no need for code as all it is, is an update query.
Thanks
When writing out the form, save the current states in the $_SESSION-variable. The check the submitted forms and compare with the data in the $_SESSION-variable. Then only make an update on the forms that have changed.
if($_SESSION['name'] != $myform['name']) { $sql[] = "name = '{$myform['name']}'"; }
if($_SESSION['img'] != $myform['img']) { $sql[] = "img = '{$myform['img']}'"; }
$sqlstring = "UPDATE mytable SET " . implode(",",$sql);
// run the sql
EDIT: to implement logging:
// populate the variables (name, img) from the db/session with the highest revision number.
// ie SELECT * FROM mytable where userid = $userid ORDER BY revision DESC LIMIT 1
$revision = $_SESSION['revision'] + 1;
$sql = "INSERT INTO mytable SET img = '$img', name='$name', revision='$revision'";
Did you put all that information in a $_SESSION or something? If so, you can unset the session and declare it again, with the new info.
You can use custom setters / getters to do this. Check the code below.
You can also add additional checks to make sure the values have changed, or use magic methods to make things more dynamic.
class MyObject
{
protected $modifiedFields = array();
public function setField($value) {
if (!in_array('field', $this->modifiedFields)) {
$this->modifiedFields[] = 'field';
}
}
}
If you have the modified fields, you can just run the update query to contain only these fields.

display php forum topics list in Android

I have android app. with a php forum. for the time being I have a single user table to store the user details
but I did so coz I need to allow users to post and comments from the android interface to the forum.
I need to bring the list of topics from my forum and when user choose one of them it displays the content and he can click comment button to go to comment layout to write and send his/comments to the forum.
now I have made this php code to list the topics
<?php
//This page let display the list of topics of a category
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
if(isset($_GET['parent']))
{
$id = intval($_GET['id']);
}
$dn = mysql_query('select t.title, u.username as author, from topics as t left join topics left join user as u where t.parent="'.$id.'" and t.id2=1 group by t.id order by t.timestamp2 desc');
if(mysql_num_rows($dn)>0)
{
$dn = mysql_query("SELECT * FROM topics WHERE id = $parent");
// return user details
$posts = array();
if(mysql_num_rows($dn)) {
while($post = mysql_fetch_assoc($dn)) {
$posts[] = array('post'=>$post);
}
}
} else {
// return false;
}
?>
but I'm sure is correct or not also in my Android side should I create an array to hold this values to display..
I need to know if my concept is correct otherwise I'll be wasting my time...
thanks a lot in advance
What you need to do is to print your information in a format you can parse from Android. I suggest JSON as it's simple and the preferred way to do it.
So, to summarize:
Print your forum's information in JSON
Perform an HTTP request from Android and get the response body
Parse it with a JSON Library
Optional but recommended: Transform it into a object to represent each element (each forum)

PHP check if variable exists in all rows returned

i want to do a check if a user id exists in all of the table rows i search for.
edit sorry i was missleading i think.
I want to check if the user has read all of the articles in a category, i have a forum front end displaying the categories and within the categories are the articles.
On the categories screen i want to display an image ALL ARTICLES READ or NOT ALL ARTICLES READ, so some how i need to loop through all of the articles per category which is what the example query below is doing and check if user id exists in ALL returned rows if yes then then all articles have been read if there are some rows missing the users id then some articles have not been read
This is my sql query
$colname_readposts = "-1";
if (isset($_GET['Thread_Category_Article_id'])) {
$colname_readposts = $_GET['Thread_Category_Article_id'];
}
mysql_select_db($database_test, $test);
$query_readposts = sprintf("SELECT Thread_Article_User_Read FROM Thread_Articles WHERE Thread_Category_Article_id = %s", GetSQLValueString($colname_readposts, "int"));
$readposts = mysql_query($query_readposts, $cutthroats) or die(mysql_error());
$row_readposts = mysql_fetch_assoc($readposts);
$totalRows_readposts = mysql_num_rows($readposts);
How can i check if all of the rows returned contain the users id?
The idea is to check to see if user has read all the articles if yes show READ if no show UNREAD.
The results per row are like so 0,15,20,37 these are id's entered when a user views a post.
i have managed to get this check for a single article to show if the user has read a specific article but unsure how i would check multiple:
here is my single article check:
<?php
$userid = $_SESSION['loggedin_id'];
$userreadlist = $row_readposts['Thread_Article_User_Read'];
$myarray = (explode(',',$userreadlist));
if (in_array($userid,$myarray )){
?>
html image READ
<?php } else { ?>
html image UNREAD
<?php } ?>
Any help would be appreciated.
Carl
First up, forget the mysql_* functions; ext/mysql is a deprecated API as of PHP 5.5 - so it's a really good idea to use mysqli or PDO.
From what I gather you're actually trying to see if any of those results contain a specific user's id? If so, do this in the SQL query:
SELECT Thread_Article_User_Read FROM Thread_Articles WHERE
Thread_Category_Article_id = %s AND UserID = %s
And supply this the User's ID as a second argument. (Syntax may not be 100% correct, but it should prove a point)
If you mean you want to check there there is any user's ID - then once again; do this in SQL:
SELECT Thread_Article_User_Read FROM Thread_Articles WHERE
Thread_Category_Article_id = %s AND UserID IS NOT NULL
This will ensure there is a valid value for 'UserID'.
Naturally replace 'UserID' with your column name if you base your solution on one of these examples.
However, if you're dumping out ALL the results from a table - and you need to see if your user's ID is present in a certain column (like you do!); then you can actually just adapt the logic that you're using on your single article page. Which should give you something like this...
$userid = $_SESSION['loggedin_id'];
$colname_readposts = "-1";
if (isset($_GET['Thread_Category_Article_id'])) {
$colname_readposts = $_GET['Thread_Category_Article_id'];
}
/* connect to db and run query; CHANGE ME TO SOMETHING NOT DEPRECATED */
mysql_select_db($database_test, $test);
$query_readposts =
sprintf("SELECT Thread_Article_User_Read FROM Thread_Articles WHERE
Thread_Category_Article_id = %s", GetSQLValueString($colname_readposts, "int"));
$readposts = mysql_query($query_readposts, $cutthroats) or die(mysql_error());
/* loop through all returned items */
while($row = mysql_fetch_assoc($readposts)) {
/* repeat the check you used on an individual
row on the single article page. i.e: */
$userreadlist = $row['Thread_Article_User_Read'];
$myarray = (explode(',',$userreadlist));
if (in_array($userid,$myarray )){
/* user has read */
} else {
/* user hasn't read */
}
}
If that code you worked for a single page then it should work in the above; as for every iteration of the loop you're working on a single row - just as you were on the single page. If the data is coming from the same table then the column names etc match up and it will work.
Or, if you just want to know if there are any unread posts at all, replace the loop with this one...
/* loop through all returned items */
$read = true;
while($row = mysql_fetch_assoc($readposts)) {
/* repeat the check you used on an individual
row on the single article page. i.e: */
$userreadlist = $row['Thread_Article_User_Read'];
$myarray = (explode(',',$userreadlist));
if (! in_array($userid,$myarray )){
$read = false;
break;
}
}
if( $read ){
/* all pages are read */
} else {
/* there are unread pages */
}

Categories