I've got two tables, one called category, which has the rows id and name, and another called placecategory, which has the tables id, place_id and category_id. I need to inner join these two to echo out the names of the categories where the placecategory.place_id is equal to a $GET[ID].
I've got this so far, but it echo's out nothing.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name FROM category
INNER JOIN placecategory
ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id.'';
$result = mysqli_query($dbc,$qry);
while ($row = mysqli_fetch_array($result))
{
echo ''.$row['name'].'';
};
?>
This wont fix your query, but it will display the error generated by the incorrect query. Its a start.
I cannot solve the query issue without a better understanding of your schema.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name
FROM category
INNER JOIN placecategory ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id;
$result = mysqli_query($dbc,$qry);
// test the status before continuing
if ( ! $result ) {
echo mysqli_error($dbc);
exit;
}
while ($row = mysqli_fetch_array($result))
{
echo $row['name'];
}
?>
Related
I have one table with categories and another table with linkrecords for each category and the table structure looks like this:
categories:
id (int)
name (varchar)
links:
id (int)
link (varchar)
fk_cat_id (int)
Here is how I do now, but know that it is a no go with a query within a query:
$query = "SELECT * FROM categories";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$catid = $row['cat_id'];
echo 'CatName: '.$row['name'];
echo '<ul>';
$query2 = "SELECT * FROM links WHERE fk_cat_id = $catid";
if ($result2 = $mysqli->query($query2)) {
while ($row2 = $result2->fetch_assoc()) {
echo '<li>'.$row2['link'].'</li>';
}
}
echo '</ul>';
}
}
I guess I have to go to some JOIN method, but not sure how!
Following query will be used to retrieve links with relation to link categories.
Also, It is a good practice to specify fields name in query to retrieve specific columns only instead of *.
SELECT links.id AS link_id, links.link, links.fk_cat_id, categories.name
FROM links
JOIN categories ON categories.id = links.fk_cat_id;
I wanna be able to echo out if Groupname and Username are connected correctly, where the current userid (saved in a session) is $uid.
I've been sitting for hours trying all kinds of JOINs and the closest I've gotten is having it output 1/? members for each team, but not all of them.
EDIT:
$uid = $_SESSION['uid'];
$sql = "SELECT * FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user
INNER JOIN usergroup ON user.userid=usergroup.userid
WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
$row2 = mysqli_fetch_array($result2);
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
Thing is, that it kinda works well, except that it doesn't print all the groupmembers names out, it prints out just one. Which one seems to depend on the order in the table.
You did not have a loop on the second query's resultset. However, it is not needed to have a second SQL query. Just do it in one go; SQL was designed for that.
Also, you'll have much simpler code:
$uid = $_SESSION['uid'];
// Select everything you need in one go (join user table as well)
$sql = "SELECT group.group_id, group.groupname, user.username
FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
INNER JOIN user ON user.userid=usergroup.userid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
// Don't need to call mysqli_num_rows if you continue like this:
while($row = mysqli_fetch_array($result)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
Maybe you want to echo some <tr> and </tr> tags, or you"ll have everything in one row, like:
echo "<tr><td>".$row['groupname']."</td>"
."<td>".$row['username']."</td>"
."<td>".$row['groupid']."</td></tr>";
There you go: (you were missing nested while loop)
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user INNER JOIN usergroup ON user.userid=usergroup.userid WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
if(mysqli_num_rows($result2)>0) {
while($row2 = mysqli_fetch_array($result2)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
}
}
Side note: You could achieve the same results with just one SQL query, something like:
SELECT
*
FROM
usergroup ug
INNER JOIN
user u ON ug.userid = u.userid
GROUP BY
ug.id
and then in PHP (pseudo code just, do not copy-n-paste)
while($row => mysqli_fetch_array($result)) {
if (!isset($groupsWithUsers[$row['groupid']['users'])) {
$groupsWithUsers[$row['groupid']['users'] = array()
}
$groupsWithUsers[$row['groupid']['users'][$row['userid']] = $row;
}
I have a query that will display the fields/values of a table that is related to other table.Using foreach loop, I can display those fields/values in html.But I want to display the the 'foreign_name' instead of 'foreign_id'.
<?php foreach ($table_related as $table): ?>
<?php echo $table['id']; ?>
<?php echo $table['foreign_id']; ?>//the foreign key, it should be foreign_name
<?php echo $table['name'];?>
<?php endforeach; ?>
//classeManageService.php
function showAllServices()
{
$query = $this->link->query("SELECT * FROM services ORDER BY id DESC");
$rowcount = $query->rowCount();
if($rowcount > 0)
{
$result = $query->fetchAll();
return $result;
}
else
{
return $rowcount;
}
return $result;
}
//show_all.php
<?php
include_once('../../classes/class.ManageServices.php');
$init = new ManageServices();
$show_all_services = $init->showAllServices();
?>
'my_table' has columns id,my_name,desc,foreign_id and 'other_table' has columns foreign_id,foreign_name,foreign_desc
I can display all those values in html.But how about displaying the other fields instead of its id from the other table?Do I have to change my query?Any Ideas?
You have to do a query with a JOIN:
Since you didn't provide the other table name, please consider otherTable as it, and service_id as foreign key.
Query example:
$query = $this->link->query("SELECT * FROM services s, otherTable o WHERE s.id = o.service_id ORDER BY s.id DESC");
now in the result set you will have also all the fields of otherTable from which you will be able to get the name as desired.
ok I got it, I change my query
From
$query = $this->link->query("SELECT * FROM services ORDER BY id DESC");
into
$query = $this->link->query("SELECT services.*, services_type.name FROM services JOIN services_type USING(services_id)") ;
Now its working, Yayy..
I'm dealing with a junction table for a many to many relationship between products and categories. With this particular function I'm attempting to take in a product_ID variable and get all associated category names in an array. However, with the current setup I'm only getting one category per product ID when I know several have 2. Any thoughts? Also anyone know of a good simple solution to more visually keeping track of M2M relationships in mysql?
//INPUT PRODUCT ID, GET ASSOCIATED CATEGORIES
function productcat($pid) {
global $sql;
$query = "SELECT * FROM Product_Category WHERE Product_ID = '$pid'";
$result = mysqli_query($sql, $query);
$catidarray = array();
while($row = mysqli_fetch_array($result)) {
array_push($catidarray, $row['Category_ID']);
}
foreach($catidarray as $i) {
$query = "SELECT * FROM Categories WHERE Category_ID = '$i'";
$result = mysqli_query($sql, $query);
$namearray = array();
while($row = mysqli_fetch_array($result)) {
array_push($namearray, $row['Name']);
}
}
return $namearray;
}
There is something wrong with your function.
In your second foreach, you put the variable $namearray inside the loop which on every run resets its value to empty array $namearray = array();. Just put that outside the foreach:
//--> put it here
$namearray = array();
foreach($catidarray as $i) {
$query = "SELECT * FROM Categories WHERE Category_ID = '$i'";
$result = mysqli_query($sql, $query);
while($row = mysqli_fetch_array($result)) {
array_push($namearray, $row['Name']);
}
}
And, I just want to make some suggestions on your function. Since you have the junction table, you don't really need to have a separate query for product and category in order to get your desired values from those tables.
Just do the INNER JOIN to maximize the use of your table relations.
Use your junction table Product_Category because that's the real purpose why created that.
SELECT *
FROM Product_Category AS a
INNER JOIN Category AS b
ON a.Category_ID = b.Category_ID
WHERE Product_ID = $pid
In your function, you may try this: havent tested but hope this will give you idea.
//INPUT PRODUCT ID, GET ASSOCIATED CATEGORIES
function productcat($pid) {
global $sql;
$query = "SELECT *
FROM Product_Category as a
INNER JOIN Category as b
ON a.Category_ID = b.Category_ID
WHERE Product_ID = {$pid}";
$result = mysqli_query($sql, $query);
$namearray = array();
while($row = mysqli_fetch_array($result)) {
array_push($catidarray, $row['Name']);
}
return $namearray;
}
Then that's it :)
And by the way, in the latest version of php, mysql_ functions are already deprecated. Much better if you will be going to use PDO or MySQLi.
Check this also: PDO vs. MySQLi
I am using a code something like below to get data from the second table by matching the id of first table. Code is working well, but I know it slow down the performance, I am a new bee. Please help me to do the same by an easy and correct way.
<?php
$result1 = mysql_query("SELECT * FROM table1 ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ))
{
$tab1_id = $row1['tab1_id'];
echo $row['tab1_col1'] . "-";
$result2 = mysql_query("SELECT * FROM table2 WHERE tab2_col1='$tab1_id' ") or die(mysql_error());
while( $row2 = mysql_fetch_array( $result2 ))
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
}
?>
You can join the two tables and process the result in a single loop. You will need some extra logic to check if the id of table1 changes, because you'll only want to output this value when there's a different id:
<?php
// Join the tables and make sure to order by the id of table1.
$result1 = mysql_query("
SELECT
*
FROM
table1 t1
LEFT JOIN table2 t2 ON t2.col1 = t1.id
ORDER BY
t1.id") or die(mysql_error());
// A variable to remember the previous id on each iteration.
$previous_tab1_id = null;
while($row = mysql_fetch_array( $result1 ))
{
$tab1_id = $row['tab1_id'];
// Only output the 'header' if there is a different id for table1.
if ($tab1_id !== $previous_tab1_id)
{
$previous_tab1_id = $tab1_id;
echo $row['tab1_col1'] . "-";
}
// Only output details if there are details. There will still be a record
// for table1 if there are no details in table2, because of the LEFT JOIN
// If you don't want that, you can use INNER JOIN instead, and you won't need
// the 'if' below.
if ($row['tab2_col1'] !== null) {
echo $row['tab2_col2'] . "-";
echo $row['tab2_col3'] . "</br>";
}
}
Instead of having 2 while loops, what you can do is join the 2 tables and then iterate over the result.
If you're not sure what join is look here: https://dev.mysql.com/doc/refman/5.1/de/join.html
Also here is a fairly simple query written using join: Join Query Example
You can use this. One relation with two tables:
<?php
$result1 = mysql_query("SELECT tab2_col2, tab2_col3 FROM table1, table2 where tab2_col1 = tab1_id ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ),)
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
?>
Like Sushant said, it would be better to use one JOIN or simpler something like that:
SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id