I have 3 tables, members, teams & team_members.
team_members houses the ids from both the members & teams and stores them per row.
The schema of theteam_members table:
teams table:
What I'd like to be able to do is create a join where i can output the team_name from the teams table and then underneth show the members_firstname associated with that that team. So example:
Team 1
joe bloggs
jon doe
Team 2
charlie chaplin
hulk hogan
My php code looks like this:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$sql = "SELECT t.team_name, group_concat(m.firstName)
FROM members AS m
JOIN team_members AS tm
ON tm.member_id = m.member_id
JOIN teams as t
on t.team_id = tm.team_id
GROUP BY t.teamname";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $row["member_id"] . '<br>';
echo $row["team_id"] . '<br><br>';
}
}
?>
Now I get:
Notice: Trying to get property of non-object in -- on line 30 which is:
if($result->num_rows > 0){
You should use two joins to piece together the three tables.
SELECT t.team_name as team_name, group_concat(m.firstName) as team_members
FROM members AS m
JOIN team_members AS tm
ON tm.member_id = m.member_id
JOIN teams as t
on t.team_id = tm.team_id
GROUP BY t.team_name
You then should check the status of your query before trying to work with it.
if(!$result = $conn->query($sql)) {
die(printf("Errormessage: %s\n", $conn->error));
}
Then loop through the results, and split the grouped values by the comma.
while($row = $result->fetch_assoc()){
echo $row["team_name"] . '<br>';
$names = explode(',', $row['team_members']);
foreach($names as $name) {
echo $name . '<br>';
}
echo '<br>';
}
You also could use <br> as the separator in the group_concat. You can read more about that function here, http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat. If you did that you can get rid of the foreach and explode because the $row['team_members'] would be built with a linebreak for each member.
The easy way to do this in PHP is width two nested loops in first you go trought the team table and print it in the second you print all the playes width theat team id...
Something like:
do{
echo $row_team;
do{
echo $row_playa;
}while($row_plya = mysql_fetch_assoc($playas)); // whear pleya.team_id = $row_team.id
}while($row_team = mysql_fetch_assoc($teams));
Related
I am trying to make a forum kind of thing for myself so I can learn from it. Now I need it to only show the 'topics' from a board with the right board_id as you can see on the first picture that are the boards and the second picture is the database with the topics so if I click on 'Nieuws & Events' board it only needs to show me the record with the topicnaam(topicname) = salespage.
I am only strugling to get this and I am not really sure what to do.
Ps. This is my first question so tell me if I am doing something wrong or if I am missing some important information.
Database with the main boards
Database with the forum topics
** The code to show the topics:**
<?php
$toppic = $app->get_topics();
foreach($toppic as $topic){
echo '<a href="https://tom.lbmedia.nl/reactie"> <div id="topic">';
echo '<div id="topicimg">';
if(file_exists('assets/images/profielfotos/'.$topic['klant_id'])) {
echo '<img class="img-circle" src="/assets/images/profielfotos/'.$topic['klant_id'].'/'.$topic['foto'].'" />';
} else {
echo '<i class="fa fa-fw fa-user img-circle"></i>';
}
echo '</div><div id="topictekst">';
echo '<b>'.$topic['topicnaam'].'</b>';
echo ' - ' . $topic['voornaam'] . " " . $topic['achternaam'] ;
echo '<span style="float:right; margin-top:15px; margin-left:5px;">reacties</span> <span style="float:right; color:grey; margin-top:15px"class="fa fa-comment"></span>';
echo '<hr><span class="badge bg-red">' . $board['topic'] . '</span>';
echo '</div></div></a>';
}
?>
The functions I am using:
public function get_boards(){
$getBoards = $this->database->query("SELECT boards.*, ledenpagina.ledenpagina_id FROM boards
LEFT JOIN ledenpagina ON ledenpagina.ledenpagina_id = boards.ledenpagina_id
ORDER BY id DESC");
// $this->database->bind(":ledenpagina_id", $_SESSION['ledenpagina_id']);
$boards = $this->database->resultset();
return $boards;
}
public function get_topics(){
$getTopic = $this->database->query("
SELECT topics.*, klanten.foto, klanten.voornaam, klanten.achternaam FROM topics
LEFT JOIN klanten ON topics.klant_id=klanten.id
ORDER BY id ASC");
// $this->database->bind(":ledenpagina_id", $_SESSION['ledenpagina_id']);
$topics = $this->database->resultset();
return $topics;
}
Your code is:
If you have in input the board id:
SELECT t.* FROM topics t
JOIN boards b
ON t.borad_id = b.id
WHERE b.id = 2
or
SELECT t.* FROM topics t
WHERE t.borad_id = 2
If you have in input board description:
SELECT t.* FROM topics t
JOIN boards b
ON t.borad_id = b.id
WHERE b.description = 'Nieuws & Events'
Use Join
Here is an example:
SELECT Boards.id, Boards.topic, Topics.board_id, Topics.topicnaam
FROM Boards
INNER JOIN Topics
ON Boards.id=Topics.board_id
WHERE Boards.id = 2;
I have a BusinessID in both my staff and business table and I'm wanting to display the staff members for everyone in a particular business. The query below gives me this error.
ERROR: Could not able to execute SELECT * FROM business b inner join BusinessID b ON b.BusinessID = s.BusinessID WHERE b.BusinessID = 1. Not unique table/alias: 'b'
This is my foreign key file
<html>
<body>
<?php
include_once("connect.php");
$BusinessID = $_GET['BusinessID'];
$sql= "SELECT *
FROM business b
inner join BusinessID b
ON b.BusinessID = s.BusinessID
WHERE b.BusinessID = $BusinessID";
if($result = $conn->query($sql)){
if($result->num_rows > 0){
echo "<table>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>BusinessID<th>";
echo "</tr>";
while($row = $result->fetch_array()){
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['BusinessID'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
$result->free();
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . $conn->error;
}
// Close connection
$conn->close();
?>
</body>
</html>
Below is the fix
$sql= "SELECT *
FROM staff
WHERE BusinessID = $BusinessID";
You need to use a join statement
Select *
From staff as S
Join business as B
on s.businessID=b.businessID
--Where clause <--- If you want to filter by anything.
You say you "have a BusinessID". If it were in $BusinessID, the form of query you want seems to be:
query select * from staff where s.BusinessID = $BusinessID
However be warned of SQL code injection as addressed at How can I prevent SQL injection in PHP? (See also the coincidental meta post from today Should the answer be the simplest ever possible, even at the expense of quality/security?) The correct way to deal with this in a PHP context is to query via prepared statements.
I am trying to get a query working that shows specific info from a mult-select-field that is part of a phpbb forum.
SELECT d.pf_firstname, d.pf_lastname, d.pf_specialism
FROM phpbb_profile_fields_data d
WHERE d.pf_lastname = 'Linssen'
The query above gives the following Result:
-- firstname: Pierre
-- lastname: Linssen
-- pf_specialism: 1;3;8;10;12;15;16 (which are the selected options)
In another table the relation between the available options (0 to 18)
and the related text is given.
result of a "wrong" query, showing all these options
The query I need should show: firstname and lastname of a user and only the specific options that that user (in this case: Linssen) has selected for a specific profile field (in this case: specialism).
So the result of the query should be something like
-- firstname: Pierre
-- lastname: Linssen
-- specialism: (1) Counseling ; (2) Executive Coaching ; (8) Oplossings gericht coachen; (10) Provocatief coachen ; (12) Sales coaching ; (15) Team coaching ; (16) Wandel coaching
How do I do that?
In order to support multi-language, profile fields values (TEXT) are stored in the _lang table, and the actual _data table only holds indexes to the lang table. So that you have, say, 3 stored in the data table, and then you map that to "Project Manager" in English or "Gestor de Proyectos" in Spanish...
2017-01-22: Thanks for input sofar still struggling to get the query to work.
Please find below the three tables with their relevant content.
phpbb_profile_lang has the following relevant fields
-- field_id (41)
-- lang_id (2)
-- lang_name (specialisme)
phpbb_profile_fields_data has the following relevant fields
-- user_id (90)
-- pf_voornaam (Pierre)
-- pf_achternaam (Linssen)
-- pf_specialisme (1;3;8;10;12;15;16)
phpbb_profile_fields_lang has the following relevant fields
-- field_id (41)
-- lang_id (2)
-- option_id (0) lang_value (Business Coaching)
-- option_id (1) lang_value (Counseling)
-- option_id (2) lang_value (Executive Coaching)
-- option_id (3) lang_value (Holistische Coaching)
-- ...............................................
-- ...............................................
-- option_id (17) lang_value (Zingeving)
-- option_id (18) lang_value (Overige)
Your query to join the tables would look like this:
select pf_voornaam, pf_lastname, lang_value
from phpbb_profile_fields_data pfd
inner join phpbb_profile_fields_lang pfl on pfl.feld_id = pfd.pf_specialisme
inner join phpbb_profile_lang pl on pfl.lang_id = pl.lang_id;
If you have control of the schema, I would strongly recommend to change phpbb_profile_lang.lang_id to be the primary key field_id and remove the lang_id - this is redundant based on the data you've shown.
Based on your example, I have used the following query:
select pf_voornaam, pf_achternaam, pf_specialisme, lang_value
from phpbb_profile_fields_data pfd
inner join phpbb_profile_fields_lang pfl on pfl.field_id = pfd.pf_specialisme
inner join phpbb_profile_lang pl on pfl.lang_id = pl.lang_id;
The result is shown in this image
With all the relevant input here and with help of "Javiexin", the following mysqli-based php-script with the various included mysql-queries did the trick. I am open to any suggestions to further improve the queries and script.
Here is a link to a result page.
<?php
/*Open connection to our database. */
$link = mysqli_connect("localhost", "perspec1", "FLeur0798!", "perspec1");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* check if server is alive */
if (mysqli_ping($link)) {
printf ("A: Our connection is OK!<br/><br/>");
} else {
printf ("Error: %s\n", mysqli_error($link));
}
/* First MYSQL query */
$sql = "SELECT d.pf_voornaam, d.pf_achternaam, d.pf_specialisme FROM phpbb_profile_fields_data d WHERE d.pf_achternaam = 'Linssen'";
if (!$sql) { echo "Error: ".mysqli_error(); die();
} else {
printf ("B: First query is successful!<br/><br/>");
}
if ($result = mysqli_query($link, $sql))
{
echo "<table>";
//header
echo "<tr><td>Voornaam</td>";
echo "<td>Achternaam</td>";
echo "<td>Specialisme</td></tr>";
//data
while ($row = mysqli_fetch_array($result))
{
echo "<tr><td>{$row[0]}</td>";
echo "<td>{$row[1]}</td>";
echo "<td>{$row[2]}</td></tr>";
}
echo "</table><br/>";
}
/* Second MYSQL query */
$query2 = mysqli_query($link, $sql );
if (!$query2) { echo "Error: ".mysqli_error(); die();
} else {
printf ("C: Second query is successful!<br/><br/>");
}
while( $row = mysqli_fetch_assoc($query2))
$selected_opts = explode (";", $row['pf_specialisme']);
foreach ($selected_opts as $selected_opt) echo "$selected_opt <br/>";
echo "<br/>";
$selected_opts_string = implode(', ', $selected_opts);
$sql3 = "SELECT fl.option_id, fl.lang_value FROM phpbb_profile_fields f, phpbb_profile_fields_lang fl WHERE f.field_id = fl.field_id AND f.field_name = 'specialisme' AND fl.lang_id = 1 AND fl.option_id IN ($selected_opts_string) ORDER BY fl.option_id ASC";
$query3 = mysqli_query($link, $sql3 );
if (!$sql3) { echo "Error: ".mysqli_error(); die();
} else {
printf ("D: Third query is successful!<br/><br/>");
}
if (!$query3) { echo "Error: ".mysqli_error(); die(); }
echo "<table>";
while( $result = mysqli_fetch_assoc($query3) )
{
echo "<tr><td>$result[option_id]</td>";
echo "<td>$result[lang_value]</td></tr>";
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($link);
?>
Up until now I have just been using one table in a MySQL query, but now I am using two tables in a query to return only users' favourites, i.e.:
$query1="SELECT tracks.id, favourites.track FROM tracks, favourites WHERE tracks.id = favourites.track";
$result=mysql_query($query1) or die(mysql_error());
I am wondering how then I would refer to columns in rows in just the tracks table to construct variables from this query. Previously I used:
while ($row = mysql_fetch_array($result)) {
$title = $row['title'];
...etc
}
But obviously this needs adapting to refer to just the rows in the tracks table, but how do I do this?
You can do the same using:
$query1="SELECT T.id as Tid, F.track , T.title as Title FROM tracks T inner join favourites F ON T.id = F.track";
$result = mysql_query($query1);
while ($row = mysql_fetch_object($result))
{
$title = $row->Title;
$tid = $row->Tid;
/*...etc...*/
}
I have the following query, and would like to list only the first match.
$first = $_GET['category'];
$first = $first[0] . "%";
$query = mysql_query("SELECT * FROM lyrics WHERE authorclean LIKE '".$first."'") or die(mysql_error());
(?category=b)
So DISTINCT could do this right? This is what I tried, but did not work:
$query = mysql_query("SELECT DISTINCT authorclean FROM lyrics WHERE authorclean LIKE '".$first."'") or die(mysql_error());
EDIT: Here is the full code:
function getCategory() {
$first = $_GET['category'];
$first = $first[0] . "%";
$query = mysql_query("SELECT DISTINCT authorclean FROM lyrics WHERE authorclean LIKE 'B%'") or die(mysql_error());
//$query = mysql_query("SELECT * FROM lyrics WHERE authorclean LIKE '".$first."'") or die(mysql_error());
if(mysql_num_rows($query) == 0) {
echo "Geen resultaten gevonden.";
} else {
while ($row = mysql_fetch_assoc($query)) { ?>
<p><?= $row['author']; ?></p>
<?php }
}
}
(B% is just for testing)
If I run this following query in the database directly I get two results. If I run with the code above I just get an empty page (except for the html thats already there).
SELECT DISTINCT authorclean FROM lyrics WHERE authorclean LIKE 'B%'
You should use LIMIT 1 to list only the first match.
If you have a a table "tbl_lyrics" with fields: author lyrics year and is filled for example as follows:
author_A lyrics_A year_A
author_A lyrics_A1 year_A1
author_A1 lyrics_A2 year_A
author_B lyrics_B1 year_B1
if you do
select distinct(author) from tbl_lyrics where author like '%author_A%'
you are going to get: author_A and author_A1. NOT the first one that matches.
If you want the first one that matches you can do:
select author from (select distinct(author) as author from tbl_lyrics where author like '%author_A%') where rownum <2;
this will return author_A only.
Limit is used with MySql but would not work with oracle databases