Mutlitple printing values in one field - php

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";

Related

Selecting specific data using table joins

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";

PHP, MySQL - JOINs

I am new to PHP and I just cannot figure out my code. I am using MySQL and PHP.
table: person
PK: personID
Other fields: lastName, firstName, hireDate, imgName
table: validMajors
PK: majorAbbrev
Other Fields: majorDesc
(Junction) table: personMajors
personID, majorAbbrev
When I run my code (using NATURAL JOIN) it will display the image, last&first name, and hire date. Which is great! But I need it to display their majors as well (I would like the majorAbbrev to be displayed). It also does not display people who are in the person table but are not in the personMajors table, which is an issue because we have staff members in the person table (who do not have a major since they are not a student)
Here is my code:
<table align="center">
<?php
$connection = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);
if ( mysqli_connect_errno() ) {
die( mysqli_connect_error() );
}
$sql = "SELECT * FROM person NATURAL JOIN personMajors ORDER BY lastName";
if ($result = mysqli_query($connection, $sql)) {
// loop through the data
$columns=4;
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
if($i % $columns ==0){
echo "<tr>";
}
echo "<td class='staffImage badgeText frameImage displayInLine'>" . "<img src='images/staff/".$row['imgName'].".jpg'>". "<br>".
"<strong>" . $row['firstName'] . "</strong>" ." ".
"<strong>" . $row['lastName'] . "</strong>" . "<br>" .
"Hire Date: ".$row['hireDate'] ."</td>";
"Major: " .$row['majorAbbrev'] ."</td>"; //Does not display
if($i % $columns == ($columns - 1)){
echo "</tr>";
}
$i++;
}
// release the memory used by the result set
mysqli_free_result($result);
}
// close the database connection
mysqli_close($connection);
?>
</table>
Any ideas/solution will be greatly appreciated!
Because you are not concatenating your php properly. You ended (;) your echo after displaying the $row["lastName"].
You can try these to join the three tables:
SELECT * FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Or you can define what columns to call in your query:
SELECT person.personID,
person.lastName,
person.firstName,
person.hireDate,
person.imgName,
validMajors.majorAbbrev,
validMajors.majorDesc
FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Then you can call the results with the way you are calling it right now (cleaner version):
echo '<td class="staffImage badgeText frameImage displayInLine">
<img src="images/staff/'.$row["imgName"].'.jpg"><br>
<strong>'.$row["firstName"].'</strong>
<strong>'.$row["lastName"].'</strong><br>
Hire Date: '.$row["hireDate"].'
Major: '.$row["majorAbbrev"].'
</td>';
(Second try): Is the person to major relationship one to one or one to many?
OK, this SELECT Statement should work:
SELECT person.*, validMajors.* FROM person AS p, validMajors AS vm, personMajors AS pm WHERE p.personID = pm.personID AND pm.majorAbbrev = vm.majorAbbrev

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>";
}

Echo number of rows per group by

I have a mysql query in which I group each post by the date is was posted. I want to be able to echo the amount of posts that happened each day, know a way?
Here is what I've written so far which does post a new <div> for each day it was posted.
$trendQuery = "
SELECT DATE(timestamp) AS ForDate,
COUNT(*) AS NumPosts
FROM trends
WHERE `trend` = '" . $_GET['graph'] . "'
GROUP BY DATE(timestamp)
ORDER BY ForDate
";
$result = mysql_query($trendQuery);
while ($row = mysql_fetch_array($result)) {
echo'
<div>
<p>Here is where I want to say how many posts that happened!</p>
</div>
';
}
You have your query pretty much set up. To echo the results, you simply need to refer the columns with the alias name, in your case ForDate and NumPosts
$trendQuery = "
SELECT timestamp AS ForDate,
COUNT(*) AS NumPosts
FROM trends
WHERE `trend` = '" . $_GET['graph'] . "'
GROUP BY timestamp
ORDER BY ForDate
";
$result = mysql_query($trendQuery);
while ($row = mysql_fetch_array($result)) {
echo'
<div>
Date: '.$row['ForDate'].' ---- Number of Posts: '.$row['NumPosts'].'<br />
</div>
';
Create a view of your trend query and inner join it with "Select (Id or day that you want to merge) From trend"
i hope that helps

PHP Display MYSQL Results within a loop

I have a left join, code shown below that takes,
id
referrer
search term
client_id
From table 1 and then takes the following columns from table 2 using the left join query underneath.
client_id
visit_id
timedate
url1
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){ ?>
<div id=''>
<?php "<br />";
echo $row['referrer']. " - ". $row['search_term'];
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo "<br />"; ?>
</div>
<?php
}
What I am trying to do is format the rows so the referrer and search term only shows once and not on every line so that the results would look like this.
Referrer Search term
timedate url1 1
timedate Url1 1
timedate url1 1
referrer Search Term
timedate Url1 2
timedate Url1 2
timedate Url1 2
the numbers 1 and 2 are to represent different visit id's by which the results are grouped. At the moment i get the referrer and search term after every row because it is in the loop and understand that. Just don't know if i can show the referrer and searc term just once per group of results.
You have to save the current pending referrer-searchterm combination and check if it changes, if yes, print out the referrer-searchterm line:
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate" .
"ORDER BY referrer, search_term";
$result = mysql_query($query) or die(mysql_error());
$currentReferrerSeatchTerm = null;
while($row = mysql_fetch_array($result)){
$newReferrerSearchTerm = $row['referrer']. " - ". $row['search_term'];
echo '<div id=""><br>';
if($currentReferrerSeatchTerm != $newReferrerSearchTerm){
echo $newReferrerSearchTerm . '<br>';
$currentReferrerSeatchTerm = $newReferrerSearchTerm
}
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo '<br></div>';
}
I usually set a var to store the referrer then check that on each loop through. If it's the same as the previous, do nothing. If it's different, display the new header info (referrer & search_term in your case) and then update the var.
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate";
$result = mysql_query($query) or die(mysql_error());
$prevRef = '';
while($row = mysql_fetch_array($result)){ ?>
<div id=''>
<?php "<br />";
if($prevRef != $row['referrer']) {
echo $row['referrer']. " - ". $row['search_term'];
$prevRef = $row['referrer'];
}
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo "<br />"; ?>
</div>
<?php
}

Categories