I am working on a messaging system for one of my sites and I'm having a lot of issues with getting the messages to show up. For some reason I can't get the syntax right so that it will take every single value that matches the receiver_id will display if the user_id matches the receiver_id. I had it working fine on my windows test machine, but when I uploaded it to my ubuntu server it broke. So now I'm trying to fix the code. What I have is this:
$m = "SELECT m.message_id, m.receiver_id, m.sender_id, m.subject, m.body, m.posted, u.id, u.username FROM messages m, users u WHERE u.id = {$_SESSION['id']}";
$b = mysqli_query($dbc, $m);
?>
<div class="mailbox">
Inbox<br />
Sent<br />
</div>
<div class="mailbox">
<h2>Messages for <?php echo $_SESSION['username']; ?></h2>
<?php echo output_message($message); ?>
<div id="messages">
<?php
if (mysqli_num_rows($b) > 0) {
while ($mess_row = mysqli_fetch_array($b, MYSQLI_NUM)) {
$u = "SELECT * FROM users WHERE id={$mess_row[1]}";
$rec = mysqli_query($dbc, $u);
$rec_row = mysqli_fetch_array($rec, MYSQLI_NUM);
$s = "SELECT * FROM users WHERE id={$mess_row[2]}";
$send = mysqli_query($dbc, $r);
$send_row = mysqli_fetch_array($send, MYSQLI_NUM);
echo "$mess_row[3] Posted by: <b>$send_row[1]</b> on: $mess_row[5]<br /><hr />";
}
} else {
echo "No messages.";
}
What am I doing wrong? I thought I had it fixed but then it just spit out the same record five times. I tried grouping which only gave me 1 record. I tried moving the $s call outside the while loop but I'm not able to draw on the sender's user_id that way. I just don't know what to do and I've searched all over for the past several hours and I can't find exactly what I'm looking for, or else I'm not typing the question right.
Thanks in advance.
Use a JOIN to get everything in one query:
$m = "SELECT m.message_id, m.receiver_id, m.sender_id, m.subject, m.body, m.posted, s.username sender_name, r.username receiver_name
FROM messages m
JOIN users r ON r.id = m.receiver_id
JOIN users s ON s.id = m.sender_id
WHERE u.id = {$_SESSION['id']}";
I apologize for hastily throwing this together. Hope it helps.
Use this as your query, then you won't have to go through and do that horrible extra set of queries to get the user info.
$id = $dbc->real_escape_string($_SESSION['id']);
$m = "SELECT m.message_id, m.receiver_id, m.sender_id, m.subject, m.body, m.posted, u.id, u.username
FROM messages m
INNER JOIN users u ON m.receiver_id=u.id
WHERE u.id = '$id';";
Extra note: Your need to escape your session id string. I'd probably also verify it is just numbers using a regex.
edit: Use #Barmar answers query in place of mine. I'd still add the escaping/regex though.
Related
I have a simple blog where I'm practicing some php and mysql. I'm trying to display the username of the post author (you know where it says posted by Author).
I have two tables blog_members and blog_posts which are related 1 to many so I got a memberID field into the blog_posts. I'm trying to get the username of the member who's the author of the post.
I was thinking to do a join or something but I can't figure this out.
Here's what I was trying to do but it's not working because I'm sure I'm not using it properly.
$query1 = "SELECT username from blog_members JOIN blog_posts ON memberID = memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
PS: I got it working one way by using SESSION to get the userID but that works only if the user is logged is which is not the case, I want to display the name in any case.
Thanks!
Use inner join this way
And with a proper sanitize use $your_user_id for match
$query1 = "SELECT username
from blog_members
INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID
WHERE blog_posts.memberID = '" .$your_user_id . "';";
JOIN syntax is wrong in your query.
Use following query:
$query1 = "SELECT username from blog_members JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
Try something like this, usng INNER JOIN :
$query1 = "SELECT blog_members.username FROM blog_members INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
reference : http://www.w3schools.com/sql/sql_join.asp
Here is a solution using a simple WHERE condition (same performance Explicit vs implicit SQL joins) :
SELECT a.username FROM blog_members a, blog_posts b WHERE a.memberID = b.memberID
But if you need more information about MySQL Join : https://www.sitepoint.com/understanding-sql-joins-mysql-database/
Hope this helps !
I tried many things from StackOverflow regarding this error but with no luck.
I try to show a reply from a comment. The reply comment is shown along with the date and hour when posted but the author who posted the reply is not shown.
The page with error is comments.php on the line $com_name = $row['comment_author'];
The code is:
<?php
$get_id = $_GET['post_id'];
$get_com = "select * from comments where post_id='$get_id'";
$run_com = mysqli_query($con, $get_com);
while($row=mysqli_fetch_array($run_com)){
$com = $row['comment'];
$com_name = $row['comment_author'];
$date = $row['date'];
echo "
<div id='comment'>
<h3>$com_name</h3><i>Said</i> on $date
<p>$com</p>
</div>
";
}
?>
Hope to sort out this error.
Thank you and best regards.
It looks like there are no column with name comment_author. But there are field user_id. You need to modify you query to below (assume user table users has fields user_name and user_id)
$get_com = "select c.date, c.comment, u.user_name as comment_author
from comments c inner join users u on c.user_id = u.user_id
where c.post_id='$get_id'";
The answer is simple. The column_author column simply does not exist in your comments table. You probably need to join the comments table with the table that actually contains the data you need.
Example:
SELECT A.*, B.`name` as comment_author FROM `comments` A
LEFT JOIN `users` B ON A.`user_id` = B.`id`
WHERE A.`post_id`='$get_id'
Remember to always properly escape your SQL queries.
I have 2 table's:
Users (id, username, email, avatar, etc...);
Friends (id, user1, user2, status);
Now I want to build on my profile page an list of my friends with there avatar(s). I'm trying for like 4 hours by myself but i don't get it... :(
BTW: this is an error i got!
Notice: Array to string conversion in /home/reduaqi158/domains/reduankurtaj.eu/public_html/snapfriends/vrienden.php on line 26
This is what i have right now:
<?php
error_reporting(E_ALL);
session_start();
$username = $_SESSION['username'];
$status = 2;
include "includes/conn.php";
$vrienden=mysqli_query($server,"SELECT * FROM vrienden WHERE status='$status' && vriend1='$username' || vriend2='$username' ");
$vriend_list = array();
while($row = mysqli_fetch_array($vrienden))
{
if ($row['vriend1'] == $username) {
$vriend_list[] = $row['vriend2'];
}
else {
$vriend_list[] = $row['vriend1'];
}
}
echo json_encode($vriend_list);
$foto=mysqli_query($server,"SELECT prof_pic FROM users WHERE username='$vriend_list['vriend1''vriend2']' ");
while($row2 = mysqli_fetch_array($foto)) {
echo "<img class='img-rounded' src=assets/profiel/".$row2['prof_pic']." alt='Card image cap'>";
}
?>
json_encode output:
["ja","amando"]
Someone who can help me pls :)
Your initial approach is very confusing.
Almost everything in your code can be substituted by single SQL query.
You can use JOIN to get all your friends with their avatars in one go:
SELECT u.username as username, u.avatar as avatar,.... <== all columns which you need
FROM `friends_table` f <== your friends table
JOIN `users_table` u <== your users table
ON (f.user1 = u.id) <== notice that i join on user1 column
WHERE u.username = '$username' && f.status = '$status'
UNION
SELECT u.username as username, u.avatar as avatar,.... <== same columns
FROM `friends_table` f <== your friends table
JOIN `users_table` u <== your users table
ON (f.user2 = u.id) <== notice that i join on user2 column
WHERE u.username = '$username' && f.status = '$status'
By this query you select all users who are in a friendship with your $username. You need union because you don't know in which field (user1 or user2) your $username is located.
NOTE: I strongly suggest using prepared statements instead of just putting '$var' inside SQL query to prevent SQL Injection.
After executing this query you can parse results and display avatars in such a way:
while($row = mysqli_fetch_array($vrienden, MYSQLI_ASSOC))
{
echo "<img class='img-rounded' src=assets/profiel/".$row['avatar']." alt='Card image cap'>";
}
I hope you got the idea.
in your while statement you have to declare a value for the array. like array[0] = value. so that you know that array position 0 has a certain value. Like what I did here below. Don't know if it's in PHP like this but certain in .net you have to declare the location of a value in an array.
while($row = mysqli_fetch_array($vrienden))
{
if ($row['vriend1'] == $username) {
$vriend_list[0] = $row['vriend2'];
}
else {
$vriend_list[1] = $row['vriend1'];
}
}
and the following
$foto=mysqli_query($server,"SELECT prof_pic FROM users WHERE username='$vriend_list['vriend1''vriend2']' ");
shouldn't it be $vriend_list['vriend1'] . $vriend_list['vriend2']'
you have to use a connect character (the . in PHP)
Hi guys in the code below you can see what my JSON returns.
{"lifehacks":[{
"id":"2",
"URLtoImage":"http:\/\/images.visitcanberra.com.au\/images\/canberra_hero_image.jpg",
"title":"dit is nog een test",
"author":"1232123",
"score":"2",
"steps":"fdaddaadadafdaaddadaaddaadaaaaaaaaaaa","category":"Category_2"}]}
What the JSON returns is fine. The only problem is it is only displaying lifehacks if it has one like or more. So what should I change about my Query so it would display lifehacks without likes aswell.
//Select the Database
mysql_select_db("admin_nakeitez",$db);
//Replace * in the query with the column names.
$result = mysql_query("select idLifehack, urlToImage, title, Lifehack.Users_fbId, idLifehack, steps, Categorie, count(Lifehack_idLifehack) as likes from Lifehack, Likes where idLifehack = Lifehack_idLifehack AND idLifehack > " . $_GET["id"]. " group by idLifehack;", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['idLifehack'];
$row_array['URLtoImage'] = $row['urlToImage'];
$row_array['title'] = $row['title'];
$row_array['author'] = $row['Users_fbId'];
$row_array['score'] = $row['likes'];
$row_array['steps'] = $row['steps'];
$row_array['category'] = $row['Categorie'];
//push the values in the array
array_push($json_response,$row_array);
}
echo "{\"lifehacks\":";
echo json_encode($json_response);
echo "}";
//Close the database connection
fclose($db);
I hope my problem is clear like this. Thank you in advance I can't figure it out myself.
You need a LEFT JOIN here. Your query has an INNER JOIN.
select
idLifehack,
urlToImage,
title,
Lifehack.Users_fbId,
idLifehack,
steps,
Categorie,
count(Lifehack_idLifehack) as likes
from Lifehack
left join Likes on idLifehack = Lifehack_idLifehack
where idLifehack > whatever
group by idLifehack;
There's an excellent explanation of the different join types here.
A couple additional points...
Use prepared statements in your PHP. Your code is wide-open to SQL Injection, which has ruined careers and led to millions of innocent people having their personal information stolen. There are plenty of web sites showing how to do this so I won't go into it here, though I'll say my favorite is bobby-tables.
Avoid the implicit join anti-pattern in your queries. This is an implicit join:
FROM a, b
WHERE a.id = b.id
Use explicit joins instead; they separate your join logic from your filtering (WHERE) logic:
FROM a
INNER JOIN b ON a.id = b.id
I have a system where I getting images out of my database, but when it does that, there is 3x of the same images.
I have tried with different ways, DISTINCT and such, but I have no clue how I fix this.
Here is my query code:
<?php
$id = $_GET['id'];
$query = "SELECT DISTINCT * FROM billeder INNER JOIN album ON fk_album_ID = $id";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result))
{
$thumb_src = 'billeder/thumb_'.$row['billeder_sti'];
$full_src = 'billeder/'.$row['billeder_sti'];
echo "
<div class='ikon'>
<a href='$full_src'>
<img src='$thumb_src' alt='' />
</a>
</div>
";
}
?>
Hope someone can help me on the way to fix this :)
Without being able to see your table structure I won't be able to give an exact answer but the likely reason is because your INNER JOIN is not setup correctly.
SELECT DISTINCT *
FROM billeder
INNER JOIN album
ON (billeder.fk_album_ID = album.pk_album_ID)
WHERE
billeder.fk_album_ID = $id
Something like the above would be the correct way to JOIN a table and using a WHERE clause to then limit the date received.
JOIN must be used with two tables columns. See example:
SELECT * FROM tableA a INNER JOIN tableB b ON a.id = b.a_id;
What you're trying to make is something like this:
"SELECT DISTINCT * FROM billeder INNER JOIN album ON
billeder.fk_album_ID = album.album_id WHERE billeder.id = $id"
You shouldn't pass an argument to the JOIN. The arguments must be used on the WHERE clause.