Select from two tables where company_id=$company->id - php

hello I have this variable $company->id
and I have function like this
<?php
function GetEmploees(){
$db = JFactory::getDBO();
$query = 'SELECT * FROM #__jbusinessdirectory_attribute_options AS c JOIN #__jbusinessdirectory_company_attributes AS cp
on c.id = cp.option_id';
$db->setQuery($query);
if( $rows = $db->loadObjectList() ) {
foreach( $rows as $row ){
echo $row->name;
}
}
}
echo GetEmploees($company->id);
?>
I want select $row->name as $company->id
how can I insert code WHERE company_id = '.$company->id.' in query?
company_id is in table #__jbusinessdirectory_company_attributes

Try
$sql = "SELECT * FROM #__jbusinessdirectory_attribute_options AS c INNER JOIN #__jbusinessdirectory_company_attributes AS cp (on c.id = cp.option_id) WHERE c.company_id = '.$company->id.'";
Should do the trick

Related

Mysql/PHP Json nested array

I got issue with nested array which seems are not Json object for some reason. When i try for e.g access jsonData["user"] it works, but when i try go deeper such as jsonData["user"]["photo_url"] then it's treated like a string and i cant access the value.
Current code:
<?php
require_once("db_connection.php");
$userId = $_GET["user_id"];
$query = "WITH user AS (SELECT id, JSON_OBJECT('display_name', u.display_name, 'photo_url', u.photo_url) AS user FROM users u WHERE id = :userId), info AS (SELECT id, JSON_ARRAYAGG(JSON_OBJECT('text', text, 'start_at', start_at, 'end_at', end_at, 'status', status)) AS information FROM report GROUP BY id), img AS (SELECT report_id, JSON_ARRAYAGG(JSON_OBJECT('name', name)) AS images FROM report_images GROUP BY report_id), cmt AS (SELECT report_id, COUNT(*) AS totalcomments FROM report_comments rc JOIN users u ON rc.user_id = u.id GROUP BY report_id) SELECT u.user, info.information, img.images, cmt.totalcomments FROM report r JOIN user u ON u.id = r.user_id LEFT JOIN info ON info.id = r.id LEFT JOIN img ON img.report_id = r.id LEFT JOIN cmt ON cmt.report_id = r.id";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Old code which worked:
<?php
require_once("db_connection.php");
require_once("functions.php");
$userId = $_GET["user_id"];
$query = "SELECT * FROM report WHERE `user_id` = :userId";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
foreach ($result as $key => $value) {
$result[$key]["user"] = getUserById($db, $value["user_id"]);
}
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Because you are aggregating some of the values as JSON in your query, you need to decode those first before attempting to use the values and then JSON encode the whole result set. You need to do that as you fetch the data, so replace:
$result = $stmt->fetchAll();
with:
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['user'] = json_decode($row['user']);
$row['images'] = json_decode($row['images']);
$row['comments'] = json_decode($row['comments']);
$result[] = $row;
}

Three SELECT and two jsons

I created a SELECT to get my communities.
And create two SELECTs to get the communities I'm following.
But I get just my communities.
I do not get the communities I'm following.
$user_id = $_GET["id"];
$row1 = array();
$row2 = array();
// get my communities
$res1 = mysql_query("SELECT * FROM communities where user_id = '$user_id'");
while($r1 = mysql_fetch_assoc($res1)) {
$row1[] = $r1;
}
// get "id" of my communities I'm following
$res = mysql_query("SELECT * FROM communities_follow where user_id = '$user_id'");
while($r = mysql_fetch_assoc($res)) {
$coid = $r["coid"];
// get my communities I'm following
$res2 = mysql_query("SELECT * FROM communities where id = '$coid'");
while($r2 = mysql_fetch_assoc($res2)) {
$row2[] = $r2;
}
}
$resp = array_replace_recursive($row1, $row2);
print json_encode( $resp );
The inner join will get you those communities only, where you are following:
SELECT c.* FROM communities c
INNER JOIN communities_follow cf ON c.id = cf.coid
WHERE cf.user_id = '$user_id';
Or, without a JOIN:
SELECT * FROM communities
WHERE EXISTS (SELECT 1 FROM communities_follow cf
WHERE c.id = cf.coid AND cf.user_id = '$user_id')
Try this sql.
SELECT * FROM communities c LEFT JOIN communities_follow cf ON c.user_id = cf.user_id where
cf.user_id = '$user_id';

Display value instead of ID mysqli

When I add $elan_category, I get category_id, instead category_title.
Tried to apply "left join" but no success. I have following tables in database:
function getElanDetail()
{
global $con;
if (isset($_GET['elan_id'])) {
$elan_id = $_GET['elan_id'];
$get_elan = "select * from elan where elan_id='$elan_id'";
$run_elan = mysqli_query($con, $get_elan);
while ($row_elan = mysqli_fetch_array($run_elan)) {
$elan_id = $row_elan['elan_id'];
$elan_category = $row_elan['elan_category'];
$elan_title = $row_elan['elan_title'];
$elan_description = $row_elan['elan_description'];
$elan_image = $row_elan['elan_image'];
$elan_contact = $row_elan['elan_contact'];
echo "
$elan_category //Getting ID of category instead Title :(
$elan_title
$elan_description
$elan_image
$elan_contact
";
}
}
}
With join you can do something like:
$elan_id = $_GET['elan_id'];
$get_elan = "SELECT * FROM `elan`
JOIN `categories` ON `categories`.category_id = `elan`.elan_category
WHERE `elan`.elan_id='$elan_id'";
$run_elan = mysqli_query($con, $get_elan);
while ($row_elan=mysqli_fetch_array($run_elan)){
print_r($row_elan);
// see the keys in $row_elan and use them accordingly
}
For subcategories try this query:
SELECT * FROM `elan`
JOIN `categories` ON `categories`.category_id = `elan`.elan_category
JOIN `subcategories` ON `subcategories`.subcategory_id = `elan`.elan_subcategory
WHERE `elan`.elan_id='$elan_id'
$elan_category = $row_elan['elan_category'];
add these two lines after above code
$cat = mysqli_fetch_row(mysqli_query($con,"SELECT category_title FROM categories WHERE category_id = $elan_category"));
$cat_name = $cat[0];
$cat_name is your category name enjoy

adding a where variable inside sql

if user select anything besides "all" it will lead to a where statement involving KodDaerah
$where = '';
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".mysql_real_escape_string($where)."
ORDER BY koddaerah.NamaDaerah ";
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
if user select all then the system will just use the current sql statement that i provided, for now im not sure what's wrong, so here is where user select the KodDaerah from drop down list box
<?php include('dbase.php');
$sql = "SELECT KodDaerah, NamaDaerah FROM koddaerah";
$result = mysql_query($sql);
echo "<select name='KodDaerah' id='KodDaerah' class='input_field' required />
<option>Pilih Daerah</option>
<option value='all'>Seluruh Pahang</option>";
while ($kod = mysql_fetch_array ($result)){
echo "<option value=".$kod['KodDaerah'].">" .$kod['NamaDaerah']."</option>
<option value='all'>Seluruh Pahang</option>";
}
echo "<?select>";
?>
The problem is now even when i select a certain KodDaerah, it will just run the provided sql query without using the WHERE statement in the $where. Can anybody help?
EDIT:
$sql = $sql . $where;
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);
try to move up the if statement:, remove mysql_real_escape_string
(escape before)
$where = '';
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".$where."
ORDER BY koddaerah.NamaDaerah ";
and then do not append $where again
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);

join 2 tables and display menu with only group name

I have 2 tables:
group
--id
--name
category
--id
--name
--group_id
and the query:
SELECT group.id AS gid, group.name AS gname,
category.id AS cid, category.name AS cname
FROM group join category
on group.id = category.group_id
and result for it is demonstrated as below:
gid--gname--cid--cname
1 ---abc----1----def
1 ---abc----2----ggg
2 ---ccc----3----eee
2 ---ccc----4----fff
I want to show a menu like this:
abc
--def
--ggg
ccc
--eee
--fff
I can't show menu as above if I use that query (infact, I can but it's hard).
What query or a way can help me do this? Thanks so much!
It's a matter of presentation, but you may find it handy to use GROUP_CONCAT() in situation like this to pack categories per group
SELECT g.id gid, g.name gname, GROUP_CONCAT(CONCAT(c.id, '|', c.name) ORDER BY c.id) categories
FROM `group` g JOIN category c
ON g.id = c.group_id
GROUP BY g.id, g.name
Here is SQLFiddle demo
and then easily explode() categories column in php while you iterate over the resultset
Just to give you an idea how php part might look like using PDO
$db = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT g.id gid, g.name gname, GROUP_CONCAT(CONCAT(c.id, '|', c.name) ORDER BY c.id) categories
FROM `group` g JOIN category c
ON g.id = c.group_id
GROUP BY g.id, g.name";
$query = $db->prepare($sql);
$query->execute();
$rows = $query->fetchall(PDO::FETCH_ASSOC);
$query = null;
$db = null;
echo '<ul>';
foreach($rows as $row) {
echo '<li>' . $row['gid'] . '-' . $row['gname'];
$categories = explode(',', $row['categories']);
echo '<ul>';
foreach($categories as $category) {
list($cid, $cname) = explode('|', $category);
echo '<li>' . $cid . '-' .$cname . '</li>';
}
echo '</ul></li>';
}
echo '</ul>';
Output:
1-abc1-def2-ggg2-ccc3-eee4-fff
basically you have to loop for each group and printing all category belong to that group.
in php u can do this:
while( $group = mysql_fetch_array( mysql_query("SELECT id, name FROM group") ) ){
echo $group[1];
while( $category = mysql_fetch_array( mysql_query("SELECT id, name from category where group_id =" . $group[0] ) ) ){
echo $category[1];
}
}
Try this:
$arr = array(
array('gid'=>1, 'gname'=>'abc', 'cid'=>1, 'cname'=>'def'),
array('gid'=>1, 'gname'=>'abc', 'cid'=>2, 'cname'=>'ggg'),
array('gid'=>2, 'gname'=>'ccc', 'cid'=>3, 'cname'=>'eee'),
array('gid'=>2, 'gname'=>'ccc', 'cid'=>4, 'cname'=>'fff'),
);
$res = array();
foreach($arr as $ar){
if(empty($res[$ar['gid']])){
$res[$ar['gid']] = array(
'gid'=>$ar['gid'],
'gname'=>$ar['gname'],
);
}
$res[$ar['gid']]['category'][] = array('cid'=>$ar['cid'],'cname'=>$ar['cname']);
}
print_r($res);

Categories