Selecting specific data using table joins - php

I am attempting to output some a user username from the user table by joining it from a questions table, the intention being I can show which user posted this specific question.
users with id, username
discussion_q id, question_text, user_id
Here is where I am at:
$sql = "SELECT q.id AS questionId, q.question_text AS questionText, q.user_id AS questionUserId, q.published AS questionPub, users.id AS userId
FROM discussion_q
JOIN users
ON questionUserId = userId
WHERE project_id = '$projectId'
ORDER BY published";
I am getting 0 results returned back to me of course. I am sure I have over engineered this or missed something simple?
Here is my php to return the results:
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<div class="twelve columns">
<p>' . $row['question_text'] . '</p>
<p>' . $row['published'] . ' by ' . $row['username'] . '</p>
</div>';
}
} else {
echo "0 results";
}
So the end goal is to output the question_text with the username of the user who posted.

$sql = "SELECT q.id AS questionId, q.question_text AS questionText, q.user_id AS questionUserId, q.published AS questionPub, users.id AS userId
FROM discussion AS q
JOIN users
ON (q.user_id = users.id)
WHERE project_id = '$projectId'
ORDER BY published";

Related

Mutlitple printing values in one field

how can i print values from mysql,i have in the table some topics and i need to print them in same row as a comment.
But the code is doing duplicates, also i insert comment into the table.
$sql = "SELECT response.date,response.session, board.id as idboard, Jmeno,Koment,Text, Nazev as 'Nazev', Prezdivka as 'Prezdivka', board.Datum as 'Datel' FROM `board` left join users on board.ID_user=users.ID join response where response.ID_board=board.ID
";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='card'>
<div class='card-header' style='color:red;background-color:lightblue;'>" . $row["Nazev"]. " <a class='float-right'>Uživatel: " . $row["Prezdivka"]. " Datum: " . $row["Datel"]. "</a></div>
<div class='card-body' style='background-color:lightgrey;'>" . $row["Text"]. "</div>
</div>
<a href='prikazy/detail.php?id='>Odpovědi<a><br> " . $row["Koment"]. " <a style='color:pink;'>" . $row["session"]. " " . $row["date"]. " </a>
<form method='post' action='index.php'> <input type='hidden' name='idboard' value=" . $row["idboard"]. " > <input type='text' class='form-control float-right' placeholder='Zadejte nový komentář...' name='komentar'> <br>
<BR><button type='submit' class='btn btn-info float-right' name='komentovat'>Komentovat</button>
</form><br><hr>";
}
} else {
echo "0 výsledků v DB";
}
$sql =
"
SELECT
response.date,
response.session,
board.id as idboard,
Jmeno,Koment,Text,
Nazev as 'Nazev',
Prezdivka as 'Prezdivka',
board.Datum as 'Datel' FROM `board`
left join users on board.ID_user=users.ID
join response where response.ID_board=board.ID
";
The structure of DB which i connect together
Table board (translated for you)
id
name
text
id_category
id_user
date
table response
id
comment
id_board
session_print_name
date
table users
id
name
username
password
date
id_privilegies
I guess the problem is in your query. So the first thing to do is clean it up, make it readable.
SELECT
response.date,
response.session,
board.id as idboard,
Jmeno,
Koment,
Text,
Nazev,
Prezdivka,
board.Datum as Datel
FROM
board
LEFT JOIN users ON board.ID_user = users.ID
JOIN response
WHERE
response.ID_board = board.ID
Now I can immediately spot that your second JOIN is missing its ON part.
That's why you get duplicates.
I don't know the structure of your database, so I cannot add it for you.
Please do not put a query in one long string. Put it in a readable format so you can debug it, like so:
$myQuery = "SELECT
response.date,
response.session,
board.id as idboard,
Jmeno,
Koment,
Text,
Nazev,
Prezdivka,
board.Datum as Datel
FROM
board
LEFT JOIN users ON board.ID_user = users.ID
JOIN response ON response.ID_board = board.ID";

Friendship system

I have two tables:
users:
user_id
user_name
...
friends:
user_id (user who sent friend request)
friend_id (user who received a friend request)
confirmed (1 = friends, 0 = friend request)
I want each user to be able to see their friends and friend requests. I have problem with displaying friends usernames. I made it work, but it's a poor solution and I want to solve this problem using only one query (if possible).
I tried:
$sql = "SELECT friends.friend_id, friends.user_id, users.user_name FROM friends
INNER JOIN users ON friends.user_id = users.user_id
WHERE friends.user_id = " . $_SESSION['user_id'] . " AND confirmed = 1
OR friends.friend_id = " . $_SESSION['user_id'] . " AND confirmed = 1;";
My problem is that it will show user_name of users that have user_id same as user_id in friends table. My query needs to check if user_id is the same as the $_SESSION['user_id'], and if it's the same then it must return user_name of the user that has the user_id the same as friend_id in friends table.
Formulate your SQL query in the following way,
$sql = "SELECT
" . $_SESSION['user_id'] . " as user_id,
IF(u2.user_id = " . $_SESSION['user_id'] . ", u1.user_id, f.friend_id) as friend_id,
IF(f.user_id = " . $_SESSION['user_id'] . ", u2.user_name, u1.user_name) as friend_username
FROM users as u1
INNER JOIN friends as f
ON u1.user_id = f.user_id
INNER JOIN users as u2
ON f.friend_id = u2.user_id
WHERE (f.user_id = " . $_SESSION['user_id'] . " OR f.friend_id = " . $_SESSION['user_id'] . ") AND f.confirmed = 1";
Here's the live demo: http://sqlfiddle.com/#!9/e10252/7
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.

Getting information from multiple using MySQLI and be able to echo results

for the past few hours, I have been trying to find a simple method of while loop echoing information from multiple tables at once. I'd like to say I've not pulled all my hair out looking, but I have.
Here is one mysqli query to get the following fields from CUSTOMER
$tid = $_SESSION['user_id']; // "id" is 1 for example
$query = "SELECT * FROM `CUSTOMER` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
};
Here is another mysqli query to get the following fields from SALE
$query = "SELECT * FROM `SALE` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
};
Could someone possibly show me how I can get both of these tables in one query so that echoing both tables information is possible at the same time instead of separately. I am not fussed how it is done, As long as it gets all from both tables for echoing purpose, that is good.
You can do it by using LEFT JOIN like this.
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
And this is your code.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `SALE`.user_id=`CUSTOMER`.user_id WHERE `SALE`.user_id={$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
}
For more info read this,
https://www.w3schools.com/sql/sql_join_left.asp
I hope this helps.
EDITED
This is for joining 3 tables,
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
LEFT JOIN table3 ON table1.column_name = table3.column_name;
In your code.
SELECT * FROM `CUSTOMER`
LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id
LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id
WHERE `SALE`.user_id={$tid};
As variable.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id WHERE `SALE`.user_id={$tid}";
You can use the following code and will help u solve Ur problem
$query = "SELECT C.*,S.* FROM CUSTOMER C,SALES S
WHERE C.user_id={$tid}
and C.user_id=S.user_id;
while ($row = mysqli_fetch_array($results)) {
echo $row['C.user_id'] . "<br><br>";
echo $row['C.c_fname'] . "<br>";
echo $row['C.c_sname'] . "<br>";
echo $row['S.s_date'] . "<br>";
echo $row['S.s_total'] . "<br>";
};
You can simply join the tables to get your expected result as shown below.
$query = "SELECT c.user_id, c.c_fname, c.c_sname, s.s_date, s.s_total FROM `CUSTOMER` AS c INNER JOIN `SALE` AS s ON c.user_id = s.user_id WHERE c.user_id = {$tid}";
Joining 3 tables example
$query = "SELECT *
FROM `CUSTOMER` AS c
INNER JOIN `SALE` AS s ON c.user_id = s.user_id
INNER JOIN `PRODUCTS` AS p ON p.product_id = s.product_id
WHERE c.user_id = {$tid}";

Getting data from my join table

I have a join table which takes the id from my respondents table respondant_id and the id from my teams table table_id.
The output is fine when I SELECT from that table so I get back the respondants ID married up with the teams ID.
I am wanting to show the respondents name from respondant_data and the team name from teams by using the values output from the join table.
I have attempted this here but I keep getting 0 results.
$sql = "
SELECT
respondant_data.respondant_id, teams.team_id
FROM
respondant_data
INNER JOIN
teams
ON
respondant_data.respondant_id = teams.team_id
WHERE
respondant_teams.team_id= 5";
$result = $conn->query($sql);
$i = 1;
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $i++ . ' ';
echo 'user_id: ' . $row["respondant_id"] . ', ';
echo 'team_id: ' . $row["team_id"];
echo '<br>';
}
} else{
echo 'no results';
}
So I want my output to be like 'John Smith', 'Central Team'
Try this query.
SELECT
resp_data.respondant_id, teams.team_id
FROM
respondant_data resp_data,
teams,
respondant_teams resp_teams
WHERE
resp_data.respondant_id = teams.team_id
and resp_teams.team_id = teams.team_id
and resp_teams.team_id = 5

Grabbing info from two different tables, assistance

I am trying to make a members page. For the rank it shows numbers so I made another table that has the rank id (1,2,3 etc) and added a name to it also.
Here is my code.
<?php
$getCoB = mysql_query("SELECT * FROM `members`
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY `id`");
$id = ($getCoB['rank']);
$rankInfo = mysql_query("SELECT * FROM `ranks` WHERE `id` = '".$id."'");?>
<h2 class="title">Council of Balance members</h2>
<style>tr:nth-of-type(odd) { background-color:#F0F0F0;}</style>
<div style='padding:5px;'>
<?php
if(mysql_num_rows($getCoB) == 0)
{
echo "There are no Council of Balance members.";
} else {
echo "<table cellpadding=20 width=100%>";
while($row = mysql_fetch_assoc($getCoB))
{
echo "<tr><td style='background-color:transparent;'><b>". $row['name']
. "</b></td><td>Rank: ".$rankInfo['name']." <br/> Role: ". $row['role']."</td>";
}
echo "</table>";
}
?>
The problem is rankInfo['name'] is not showing up. I tried to do something on this line while($row = mysql_fetch_assoc($getCoB)) and tried to make it something like this while($row = mysql_fetch_assoc($getCoB)) || while($rank = mysql_fetch_assoc($rankInfo) and changed this part <td>Rank: ". $rankInfo['name'] . " to this <td>Rank: ". $rank['name'] . " but I end up with an error. If I leave it like it is, it just shows Rank: without the name I added into my database.
You can combine your two queries into one using an inner join.
<?php
$getCoB = mysql_query("SELECT m.name as member_name, m.role, r.name as rank_name
FROM `members` as m INNER JOIN `ranks` as r ON m.rank = r.id
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY m.id");
?>
Because of how INNER JOIN works, this will only display members who have corresponding records in the ranks table. If there are some members that you want to display that have no rank record, use LEFT JOIN instead.
Then when you echo out the data, be sure to refer to the item you have fetched ($row) each time. In your code, you are referring to $rankInfo['name'], where $rankInfo is not a variable, but a mysql query from which no rows have been fetched.
while($row = mysql_fetch_assoc($getCoB)) {
echo "<tr><td style='background-color:transparent;'><b>". $row['member_name']
. "</b></td><td>Rank: ". $row['rank_name'] . " <br/> Role: " . $row['role'] . "</td>";
}

Categories