Failing to write a complex condition - php

I want to display the comments of the post that has a commnet from the logged in user.
Suppose I commented on a facebook post and with my if condition I want to display later comments of the same post.
The logged in user id = $id
I tried this condition:
if($comment_uid== $id || $row['p_post_id'] = $row['c_post_id'])
Currently its displaying all the rows
sql = "SELECT DISTINCT
c.post_id AS c_post_id,
c.comment_id,
c.comment,
c.user_id AS c_uid,
u.username,
u.dp,
c.is_marked,
p.user_id AS p_uid,
p.post_id AS p_post_id
FROM comment c
INNER JOIN user u ON c.user_id = u.id
INNER JOIN post p ON c.user_id = p.user_id
ORDER BY c.comment_id DESC";
$result = mysqli_query($con, $sql);
if ($result) {
while ($row=mysqli_fetch_assoc($noti_result)) {
$post = $row['c_post_id'];
$comment = $row['comment'];
$username = $row['username'];
$comment_uid = $row['c_uid'];
$post_uid= $row['p_uid'];
if($comment_uid== $id || $row['p_post_id'] = $row['c_post_id'])
{
echo $username also said $comment</a><br>";
}

Related

How to select comments with child comments from MySQL?

I have two tables:
'comments'
| id | content | user_id | article_id | parent_id |
'users'
| id | name | photo |
And my queries are:
<?php
$query = mysql_query("SELECT comments.id, comments.content, users.name,
users.photo FROM comments, users WHERE comments.article_id = '".$get_id."'
AND comments.parent_id = 0 AND comments.user_id = users.id");
while($res = mysql_fetch_assoc($query))
{
$id = $res['id'];
$content = $res['content'];
$name = $res['name'];
$photo = $res['photo'];
echo $photo;
echo $name;
echo $content;
$query2 = mysql_query("SELECT comments.id, comments.content, users.name,
users.photo FROM comments, users WHERE comments.article_id = '".$get_id."'
AND comments.parent_id = '".$id."' AND comments.user_id = users.id");
while($res2 = mysql_fetch_assoc($query2))
{
$id2 = $res2['id'];
$content2 = $res2['content'];
$name2 = $res2['name'];
$photo2 = $res2['photo'];
echo $photo2;
echo $name2;
echo $content2;
}
}
?>
It doesn't work properly. It shows 1 parent and 1 child comment in each nest although there are several child comments.
How can I fix and minimize it? Can it be done by using only one query?
Thank you!
JOIN the table on itself.
Change your query to:
SELECT comments.id, comments.content, users.name,
users.photo FROM comments JOIN users ON comments.user_id = users.id JOIN
comments c ON comments.id =
c.parent_id WHERE
comments.article_id = '".$get_id."'
AND comments.parent_id = '".$id."'
You don't need the second query, here's the full code:
<?php
$query = mysql_query("SELECT comments.id, comments.content, users.name,
users.photo FROM comments JOIN users ON comments.user_id = users.id JOIN
comments c ON comments.id =
c.parent_id WHERE
comments.article_id = '".$get_id."'");
while($res = mysql_fetch_assoc($query))
{
$id = $res['id'];
$content = $res['content'];
$name = $res['name'];
$photo = $res['photo'];
echo $photo;
echo $name;
echo $content;
}
?>
Just use a JOIN to fetch the comments and with all the children.
SELECT users.id userID, users.name, users.photo , childrenComments.*,
parentComments.id cpId, parentComments.content cpContent,
parentComments.user_id cpUser_id,parentComments.article_id cpArticleId
FROM users JOIN (SELECT * FROM Comment WHERE id=0) parentComments
ON users.id=parentComments.user_id LEFT JOIN Comment childrenComments
ON parentComments.id=childrenComments.parent_id;
Then you can the loop through the result to print it appropriately. This would be better as you would have to run just a single query.

Using php if...else statement with two queries

I have two queries that count the number of data for both "artists" and "groups" in my database. I want to display a message if there is data to display for either artists or groups (or both), and if the data returns 0 for both of them then not to display anything.
I have the following code which doesn't seem to work:
<?php if (($numrowsartists==0)OR($numrowsgroups==0)) {
} else {
echo "There is information to display.";
}
?>
Below are the queries I have:
$query = "SELECT COUNT(*) FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$numrowsartists = mysql_fetch_assoc($res);
$query = "SELECT COUNT(*) FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$numrowsgroups = mysql_fetch_assoc($res);
Thanks in advance. I'm sure it's probably a super basic fix but I'm still very new to php and would appreciate some help.
You should getthe value frorm the row eg using alias for column name
$query = "SELECT COUNT(*) as num_artists FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$numrowsartists = row['num_artists'];
$query = "SELECT COUNT(*) as num_groups FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$numrowsgroups = row['num_groups'];
There are several solutions, the easiest being the following:
if($numrowsartists[0]+$numrowsgroups[0] > 0)
However, as people have said, you shouldn't use mysql_* functions anymore.
Assuming the ID is user input, you should really use prepared statements.
Also, you can handle both tests in a single query:
$stmt = $con->mysqli_prepare("SELECT COUNT(1) as `count` FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = ?");
$stmt->bind_param('i',$id);
$stmt->execute();
if($stmt->get_result()->fetch_array()[0] > 0){
...
}else{
//message that nothing was found
}

MYSQLI SELECT with Limit not working

I'm trying to find the number of rows in a table in the database depending on certain conditions with a limit feature so that i can count the number of rows there are matching the condition after a certain row in the table.
Thus i created my php query:
$q = $db->query("SELECT u.*, f.* FROM updates U LEFT JOIN friends f ON f.fid = u.userid WHERE f.uid = '$userid' ORDER BY u.up_id DESC LIMIT $limitID, 9999999");
$nr = $q->num_rows;
However even if there are more rows in the database after the $limitID, it says there are no rows.
If I try this:
$q = $db->query("SELECT u.*, f.* FROM updates U LEFT JOIN friends f ON f.fid = u.userid WHERE f.uid = '$userid' ORDER BY u.up_id DESC LIMIT $limitID");
$nr = $q->num_rows;
then it works, but it doesnt count after the $limitID. Any udeas?
According yo your query, it should be like
$sql = "SELECT count(*) FROM updates U
LEFT JOIN friends f ON f.fid = u.userid WHERE f.uid = ?";
// getting stuff using prepared statements
$row = $res->fetch_row();
$num = $row[0] - $limitID;
but I doubt it's really what you need either.
Using what Your Common Sense told me I managed to find an answer to my problem, so here it is:
$limitID = $upid;
$sql = "SELECT count(*) FROM updates u
LEFT JOIN friends f ON f.fid = u.userid WHERE
(f.uid = '$userid' AND u.up_id > '$limitID')";
$res = $db->query($sql);
$row = $res->fetch_row();
$num = $row[0];
if($num == 0){
// do nothing
} else {
echo "<span class='newPosts'>" .$num. " New Post"
. (($num>1)?'s':' ') . "</span>";
}
works perfectly

CodeIgniter partially override a method

I am trying to refactor this code a bit. Originally I had two different models, both extending MY_Model. However, most of the code was repetitive so now I am having First_model extend MY_Model and Second_model extends First_model. I cleaned up most of code from Second_model that it inherits from First_model, but I have several methods within Second_model that are only slightly different from the same method in First_model. Consider the following code:
First_model
class First_model extends MY_Model
{
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date('Y');
$month = date('n');
$sql = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
post.ts_created,
UNIX_TIMESTAMP(post.ts_created) post_timestamp,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
sum(ka.karma) monthly_karma
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (SELECT
IFNULL(u_all.id, user.id)
FROM UserAccounts ua
INNER join Users u ON u.id = ua.user_id
LEFT join Users u_all ON u_all.facebook_uid = u.facebook_uid
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year}
AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
$query = $this->db->query($sql);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row["id"]] = $row;
}
return $functionResults;
}
}
Second_model
class Second_model extends First_model
{
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date("Y");
$month = date("n");
$sql = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
UNIX_TIMESTAMP(post.ts_created) ts_created,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
SUM(ka.karma) monthly_karma,
post.answer_status_flags
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (
SELECT
IFNULL(u_all.id, user.id)
FROM
UserAccounts ua
INNER JOIN Users u ON (u.id = ua.user_id)
LEFT OUTER JOIN Users u_all ON (u_all.facebook_uid = u.facebook_uid)
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year} AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
$query = $this->db->query($sql);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row['id']] = $row;
}
return $functionResults;
}
}
Notice the only thing different is the query in the $sql variable. I am wondering can I somehow make the method in the first model protected and only change the query in the second? Or is there a more efficient way to trim down this code? I have several methods this same thing applies to and it seems a bit much to keep redefining the methods in the new Class.
I would think about pass the $sql as a variable in your models:
In your First Model you would have:
private $sqlPostId = '';
public function __construct() {
$this->sqlPostId = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
post.ts_created,
UNIX_TIMESTAMP(post.ts_created) post_timestamp,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
sum(ka.karma) monthly_karma
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (SELECT
IFNULL(u_all.id, user.id)
FROM UserAccounts ua
INNER join Users u ON u.id = ua.user_id
LEFT join Users u_all ON u_all.facebook_uid = u.facebook_uid
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year}
AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
}
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date('Y');
$month = date('n');
// Here you use the defined variable in the constructor
$query = $this->db->query($this->sqlPostId);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row["id"]] = $row;
}
return $functionResults;
}
And then you just have to change the SQL in the construct function in your second Model and go.

PHP MySQL query help

I am trying to use this query to return every instance where the variable $d['userID'] is equal to the User ID in a separate table, and then echo the username tied to that user ID.
Here's what I have so far:
$uid = $d['userID'];
$result = mysql_query("SELECT u.username
FROM users u
LEFT JOIN comments c
ON c.userID = u.id
WHERE u.id = $uid;")$row = mysql_fetch_assoc($result);
echo $row['username'];
This should work
$uid = mysql_real_escape_string($d['userID']);
$result = mysql_query("SELECT u.username
FROM users u
LEFT JOIN
comments c
ON c.userID = u.id
WHERE u.id = '$uid'");
while($row = mysql_fetch_assoc($result))
{
//PRINTS ALL INSTANCES OF THE ROW
echo $row['username'];
}
what is printed from the echo above.
if you're looking to get all the results. wrap your mysql_fetch_assoc in a while loop:
$result = mysql_query("SELECT u.username
FROM users u
LEFT JOIN comments c
ON c.userID = u.id
WHERE u.id = $uid;");
while($row = mysql_fetch_assoc($result)){
echo $row['username'];
}
Try this:
$uid = $d['userID'];
$result = mysql_query("SELECT u.username
FROM users u
LEFT JOIN comments c
ON c.userID = u.id
WHERE u.id = $uid");
while($row = mysql_fetch_assoc($result))
{
echo $row['username'];
}
*EDIT:*Removed semicolon.

Categories