Select same column name from two tables - php

I have this query:
$result3 = mysql_query("SELECT posts.id, posts.date, posts.title, comments.post, comments.id, comments.date FROM posts, comments WHERE posts.id = comments.post")
or die(mysql_error());
while($row2 = mysql_fetch_array( $result3 )) {
echo $row2['title'];
}
The problem is with the posts.id , posts.date and comments.id , comments.date . How can I get out id, date for both tables $row2['....]; I tried $row2['posts.id']; but it didn't work!

Name the column in your query (this is called an column alias) like this:
SELECT
posts.id as postsID,
posts.date,
posts.title,
comments.post,
comments.id as CommentsID,
comments.date
FROM
jaut_posts,
f1_comments
WHERE
jaut_posts.id = f1_comments.post
Then you can use:
echo $row2['postsID'];
echo $row2['commentsID'];
Edit:
You may also benefit from this question I wrote and answered which discusses many common SQL queries and requests.

Use the as in your query, some thing like
select post.id as PostId, comment.id as CommentId
and then :
row["PostId"]
row["CommentId"]

while($row2 = mysql_fetch_array( $result3 )) {
$post_id = $row2[0];
$posts_date = $row2[1];
$posts_title = $row2[2];
$comments_post = $row2[3];
$comments_id = $row2[4];
$comments_date = $row2[5];
}

change
SELECT posts.id, posts.date, posts.title, comments.post, comments.id, comments.date
into
SELECT posts.id AS postsid, posts.date, posts.title, comments.post, comments.id AS commentsid, comments.date
then you can use $row2['postsid']; and $row2['commentsid'];

Create alias:
$sql = 'SELECT posts.id AS post_id, comments.id AS comment_id ...';
$row = mysql_fetch_assoc($sql);
echo $row['post_id'];
echo $row['comment_id'];
or, alternatively, you can access it by indexes (since you're using mysql_fetch_array anyway)
echo $row[0]; // posts.id

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.

Loop through two while arrays

I am making this post system with like button and count for a social networking site.
My end goal is to loop through these two sets of results together. So that the like counts goes with the individual posts as they loop. The posts and likes are in desc order. Everything matches except I can't get these while fetch results to loop together.
Post loop
<table class="postborder">
<?php
$query1 = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query1);
while($row = mysqli_fetch_array($result)) {
?>
<div id="newpost">
<tr>
<td id="userpost"><?php echo $row['username']; ?> </td>
</tr>
<tr>
<td>
<hr id="hrline">
<img id="newimgpost" src="data:image/jpeg;base64,<?php echo base64_encode($row['name']); ?>" height="500" width="500" class="img-thumnail" />
</td>
<tr>
<td id="textpost">
<?php echo $row['textpost']; ?>
</td>
</tr>
<tr>
<td id="likebutton">
<?php } ?>
</div>
</table>
Like count loop
<?php
//index.php
//session_start();
//SESSION['userid'] = (int)3;
$connect = mysqli_connect("localhost", "root", "", "snazzer");
$query2 = "
SELECT tbl_images.id, tbl_images.textpost,
COUNT(likes.id) as likes,
GROUP_CONCAT(users.name separator '|') as liked
FROM
tbl_images
LEFT JOIN likes
ON likes.postid = tbl_images.id
LEFT JOIN users
ON likes.userid = users.userid
GROUP BY tbl_images.id
ORDER BY id DESC
";
$result2 = mysqli_query($connect, $query2);
if (!$result2) {
printf("Error: %s\n", mysqli_error($connect));
exit();
}
while($row = mysqli_fetch_array($result2))
{
echo '<h3>'.$row["textpost"].'</h3>';
echo '
LIKE';
echo '<p>'.$row["likes"].' People like this</p>';
if(count($row["liked"]))
{
$liked = explode("|", $row["liked"]);
echo '<ul>';
foreach($liked as $like)
{
echo '<li>'.$like.'</li>';
}
echo '</ul>';
}
}
if(isset($_GET["type"], $_GET["id"]))
{
$type = $_GET["type"];
$id = (int)$_GET["id"];
if($type == "postid")
{
$query = "
INSERT INTO likes (userid, postid)
SELECT {$_SESSION['userid']}, {$id} FROM tbl_images
WHERE EXISTS(
SELECT id FROM tbl_images WHERE id = {$id}) AND
NOT EXISTS(
SELECT id FROM likes WHERE userid = {$_SESSION['userid']} AND postid = {$id})
LIMIT 1
";
mysqli_query($connect, $query);
header("location:profile.php");
}
}
?>
I believe you could run two queries together. It's fairly simple; just separate each query with semicolon:
$query = "SELECT * FROM tbl_images ORDER BY id DESC;
SELECT tbl_images.id, tbl_images.textpost, COUNT(likes.id) as likes, GROUP_CONCAT(users.name separator '|') as liked FROM tbl_images LEFT JOIN likes ON likes.postid = tbl_images.id LEFT JOIN users ON likes.userid = users.userid GROUP BY tbl_images.id ORDER BY id DESC";
Or separate the variable by incrementing values, you can read their documentation which explains it here.
$query = "SELECT * FROM tbl_images ORDER BY id DESC";
$query .= "SELECT tbl_images.id, tbl_images.textpost, COUNT(likes.id) as likes, GROUP_CONCAT(users.name separator '|') as liked FROM tbl_images LEFT JOIN likes ON likes.postid = tbl_images.id LEFT JOIN users ON likes.userid = users.userid GROUP BY tbl_images.id ORDER BY id DESC";
Then run your code as you normally would except you change mysqli_query to mysqli_multi_query:
$result = mysqli_multi_query( $connect, $query );
while($row = mysqli_fetch_array( $result )) {
//... code your table here ...//
}
You can also the Object-Oriented method which works pretty well:
$result = $connect->multi_query( $query );
But of course both methods should work fine. Do keep in mind, you may be vulnerable to SQL Injections with mysqli_multi_query. This is PHP's official warning:
Security considerations
The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
Considerations
You could always save both results from your while loop in an array and run them in a foreach loop or have them output individually as $array['key']. Which would be a simple workaround to your queries:
<?php
// first query
$query1 = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query1);
while($row = mysqli_fetch_array($result)) {
$array1[] = $row;
}
// second query
$query2 = "
SELECT tbl_images.id, tbl_images.textpost,
COUNT(likes.id) as likes,
GROUP_CONCAT(users.name separator '|') as liked
FROM
tbl_images
LEFT JOIN likes
ON likes.postid = tbl_images.id
LEFT JOIN users
ON likes.userid = users.userid
GROUP BY tbl_images.id
ORDER BY id DESC
";
$result2 = mysqli_query($connect, $query2);
while($row = mysqli_fetch_array($result2)) {
$array2[] = $row;
}
Once you have those records setup you can now use $array1 and $array2 to setup your table.
To get their keys and setup you can use print_r or var_dump and you will be able to see key => value pairs:
print_r( $array1 );
echo '<br />';
print_r( $array2 );

select down and up votes for each post php mysql

I have a forum where users can post questions and can upvote and downvote.
I want to get the upvote and downvote of each post.
What i did previously was do that in 3 sets queries.
$data = mysqli_query($con,"select * from posts");
while($row = mysqli_fetch_assoc($data)){
$pid = $row['post_id'];
$up = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM up WHERE post_id = $pid"))['c'];
$down = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM down WHERE post_id = $pid"))['c'];
}
Can anyone show me how can i do these things in one single query because if a get a lot of posts in 1st query then there will be lots of queries to do.
You can use subqueries and put everything in the first query.
This could be a good start :
$data = mysqli_query($con, "select posts.*, " .
"(SELECT COUNT(*) FROM up WHERE post_id = posts.post_id) as totalUp, " .
"(SELECT COUNT(*) FROM down WHERE post_id = posts.post_id) as totalDown " .
"from posts");
while($row = mysqli_fetch_assoc($data)){
// ...
}
you can use corelated subquery for this where upvotes
and downvotes are counted based on the post id
SELECT p.*,
( select count(*) from up where post_id = p.post_id ) as upVotesCount,
( select count(*) from down where post_id = p.post_id ) as downVotesCount,
FROM posts p

Sort the results of a query using results of another query

Im working on a message board of some sort and i have everything up an running except one little part, the threads need to be sorted by the date/time of the latest post in them (standard forum format), which im having lots of trouble wrapping my head around.
This is the querys im using, i know its not pretty and its not safe, i will be reworking them once i learn how to do it properly.
$sql = "SELECT Thread_ID, Thread_Title, Board_ID, Author FROM threads WHERE Board_ID='$Board_ID' LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($row = mysql_fetch_assoc($result))
{
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$getauthor = mysql_query("SELECT * FROM members WHERE Member_ID='$Author'");
while ($row = mysql_fetch_assoc($getauthor))
{
$Post_Author = $row['Post_As']; }
$postcount = mysql_query("SELECT Post_ID FROM posts WHERE Thread_ID='$Thread_ID'");
$Posts = mysql_num_rows($postcount);
$getlatest = mysql_query("SELECT * FROM posts WHERE Thread_ID='$Thread_ID' ORDER by Post_DateTime DESC LIMIT 1");
while ($row = mysql_fetch_assoc($getlatest))
{
$Post_DateTime = time_ago($row['Post_DateTime']);
$Member_ID = $row['Member_ID']; }
$getmember = mysql_query("SELECT * FROM members WHERE Member_ID='$Member_ID'");
while ($row = mysql_fetch_assoc($getmember))
{
$Post_As = $row['Post_As']; }
So what im trying to do is Sort $sql by $getlatest, i tried adding another query above $sql that did basically the same as $getlatest and then had $sql order by that but alas it just broke everything.
I know i have to make a variable to sort the $sql by but its that variable thats driving me mad.
any help would be appreciated, thanks.
current error message as requested:
Fatal error: SQL - Unknown column 'posts2.LatestPost' in 'on clause' - SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs FROM threads INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1 ON threads.Thread_ID = Sub1.Thread_ID INNER JOIN members ON threads.Author = members.Member_ID INNER JOIN posts posts2 ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.LatestPost INNER JOIN members members2 ON members2.Member_ID = posts2.Member_ID WHERE threads.Board_ID='1' ORDER BY Sub1.LatestPost DESC LIMIT 0, 25 in C:\wamp\www\forum\include\threads.php on line 86
You should be able to do it using something like this for your first query:-
$sql = "SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, MAX(posts.Post_DateTime) AS LatestPost
FROM threads
LEFT OUTER JOIN posts ON threads.Thread_ID = posts.Thread_ID
WHERE threads.Board_ID='$Board_ID'
GROUP BY SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author
ORDER BY LatestPost DESC
LIMIT $offset, $rowsperpage";
EDIT
Not tested the following but looking at your selects I think you could probably put it together into a single SELECT. Something like this:-
$sql = "SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs
FROM threads
INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1
ON threads.Thread_ID = Sub1.Thread_ID
INNER JOIN members
ON threads.Author = members.Member_ID
INNER JOIN posts posts2
ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.Post_DateTime = Sub1.LatestPost
INNER JOIN members members2
ON members2.Member_ID = posts2.Member_ID
WHERE threads.Board_ID='$Board_ID'
ORDER BY Sub1.LatestPost DESC
LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($row = mysql_fetch_assoc($result))
{
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$Post_Author = $row['Post_As'];
$Posts = $row['PostCount'];
$Post_DateTime = time_ago($row['LatestPost']);
$Member_ID = $row['LastPostMemberID'];
$Post_As = $row['LastPostMemberPostAs'];

PHP coding question

How can I grab the count value from the query MySQL query below using PHP.
Here is My MySQL code.
$dbc = mysqli_query($mysqli,"SELECT COUNT(*) FROM((SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1')
UNION
(SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.friend_id = users.user_id
WHERE users_friends.friend_id = 1
AND users_friends.friendship_status = '1')) as friends");
using SQL_CALC_FOUND_ROWS should simplify things:
$dbc = mysqli_query($mysqli,"SELECT SQL_CALC_FOUND_ROWS users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1'
");
then afterwards do
$rs = mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$rec = $rs->fetch_array();
$count = $rec[0];
This method will return the number of records that match the query, ignoring any LIMIT statement, whereas using $rs->num_rows will only give you the number of records actually returned. Depends which one you want.
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
http://us.php.net/manual/en/mysqli.query.php
Assuming that you are correctly connected to the MySQL server and your query are executed correctly, you can use the following code:
$values = mysql_fetch_row($dbc);
$count = $values[0];
Your query should look like SELECT COUNT(*) as numThings FROM xxx
The numThings is what you will reference in PHP:
$result = mysql_query("SELECT COUNT(*) as `numThings` FROM xxx");
$row = mysql_fetch_assoc($result);
$count = $row['numThings'];

Categories