Joomla nBill user / client name query - sql

I'm attempting to do a rather complex SQL query, it's getting way out of my league, I think I'm close on this, my forehead hurts now, I toss my hands up and ask for an assist.
<?php
$db =& JFactory::getDBO();
$userid = "SELECT * FROM #__users WHERE id='".$row->userid."' ";
$db->setQuery
("
select #__nbill_contact.user_id as userid, concat(#__nbill_entity.company_name, ' - ', #__nbill_contact.first_name, ' ',
#__nbill_contact.last_name) as contact_entity from #__nbill_entity
INNER JOIN #__nbill_entity_contact on #__nbill_entity.id = #__nbill_entity_contact.entity_id
INNER JOIN #__nbill_contact on #__nbill_entity_contact.contact_id = #__nbill_contact.id and #__nbill_contact.user_id > 0"
);
$user_type_detail = $db->loadAssoc();
ech $user_tpe_detail["contact_entity"]
;?>
Thanks in advance!

Related

Using the SELECT operator 'AND' only if a variable is set

What is the correct/efficient way to display results based on a variable if the variable is set? If variable is not set, the AND operator should not be used.
I apologize if this is a repeat, I clicked the suggested links and they did not make sense to me.
Near the end of code is my note with ^^^^^ marked.
For example:
$whatever = 123;
SELECT
DISTINCT terms.name as product_type_name,
tax.term_id as termidouter
FROM $wpdb->posts AS p
INNER JOIN wp_term_relationships r
ON p.ID = r.object_id
INNER JOIN wp_term_taxonomy tax
ON r.term_taxonomy_id = tax.term_taxonomy_id
INNER JOIN wp_terms terms
ON tax.term_id = terms.term_id
WHERE
tax.taxonomy = 'product_type'
AND p.post_status = 'publish'
AND p.post_type = 'product'
AND '$whatever ' = terms.term_id
^^^^ If $whatever is empty, I want to return results as if this line did not exist.
ORDER BY product_type_name
");
I was going to do an IF/ELSE but I figured that was the lazy way.
$whatever = 123;
if (empty($whatever)) {
// SELECT without the AND
} else {
// SELECT with the AND
}
You could do something like this:
AND CASE WHEN '$whatever ' IS NOT NULL THEN '$whatever ' ELSE terms.term_id END = terms.term_id
So... typically you'd want to use prepared statements, but if we're going this route, I would collect all my optional search criteria in an array as strings:
$myTerms=array();
if(!empty($whatever)) {
$myTerms[]="terms.term_id='" . $whatever . "'";
}
...
Then you can build your query easily like so:
$mySql = "SELECT * FROM whatever WHERE somefield='somevalue' ";
if(count($myTerms)>0) {
$mySql.=" AND " . implode(" AND ", $myTerms);
}
Please note that this is a basic example; you should also be checking any value you pass into your query for attacks etc.

LEFT join AND command in yii2

I want to write a query in yii2
and i dont know how to write it
i tried few things from documentaion but its not working
here is my query
SELECT notification.*,event.title,user.firstname,user.lastname FROM notification
LEFT JOIN event ON event.id = notification.source_id
AND notification.activity_type = "checkin"
Where user.firstname in (select id from user where user_id=1)
LEFT JOIN user ON user.id = notification.source_id
AND notification.activity_type = "friend"
Where user.firstname in (select id from user where user_id=1)
and here is the query i write for now,i need to add AND function just like its in the query
$query ->select(['notification.*,event.title,user.firstname,user.lastname'])
->from('notification')
->leftJoin('event', 'event.id = notification.source_id')
->leftJoin('user', 'user.id = notification.source_id');
Have you tried the following:
$query ->select(['notification.*,event.title,user.firstname,user.lastname'])
->from('notification')
->leftJoin('event', 'event.id = notification.source_id AND notification.activity_type = "checkin" ')
->leftJoin('user', 'user.id = notification.source_id AND notification.activity_type = "friend"');

Codeigniter Joining Tables - Passing Parameters

I'm attempting to join two tables while using codeigniter. I've done this same SQL query writing regular SQL. When I attempt to do the same in codeigniter, I keep getting errors. I'm not quite sure what I'm doing wrong. What do you guys think I'm doing wrong?
My function in model_data.php
function getJoinInformation($year,$make,$model)
{
//$this->db->distinct();
// here is where I need to conduct averages but lets just work on extracting info.
// from the database and join tables.
$this->db->select('*');
$this->db->from('tbl_car_description');
$this->db->join('tbl_car_description', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$result = $this->db->get();
/*
$query = $this->db->get_where('tbl_car_description',
array(
'year' => $year,
'make' => $make,
'model' => $model
)
);
if($query->num_rows()) return $query->result();
return null;
*/
}
My error message
A Database Error Occurred
Error Number: 1066
Not unique table/alias: 'tbl_car_description'
SELECT * FROM (`tbl_car_description`) JOIN `tbl_car_description` ON `d`.`id` = `p`.`cardescription_id` WHERE `d`.`year` = '2006' AND `d`.`make` = 'Subaru' AND `d`.`model` = 'Baja'
Filename: C:\wamp\www\_states\system\database\DB_driver.php
Line Number: 330
Here is the code written in SQL and it's working great. I want to do the something in codeigniter but I'm confused as to how. Any help would be much appreciated. Thanks everyone.
$sql_2 = mysql_query("SELECT ROUND(AVG(p.value),1) AS AvgPrice, ROUND(AVG(p.mileage),1) AS AvgMileage
FROM tbl_car_description d, tbl_car_prices p
WHERE (d.id = p.cardescription_id)
AND (d.year = '".$year."')
AND (d.make = '".$make."')
AND (d.model = '".$model."')
AND (p.approve = '1')");
Your CI query references the same table twice, which I assume is a typo. However, you only need include your table alias with the table name in your Active Record call:
//$this->db->distinct();
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$result = $this->db->get();
Couple issues: You need to include your table aliases and your join should have the name of the second table ...
$this->db->from('tbl_car_description AS d');
$this->db->join('tbl_car_prices AS p', 'd.id = p.cardescription_id');

Using two tables. What am I doing wrong here?

I want to create an activity feed system and my feeds (statuses) and friends are in different tables in my database. How do I connect them so that the logged in user can only receive feeds from their friends.
<?php
$sql = "
SELECT * FROM status WHERE author='(friend of logged-in user)' AND type='a'
**UNION**
SELECT * FROM friends WHERE user1='$user' AND accepted='1' OR user2='$user' AND accepted='1'
";
$query = mysqli_query($database, $sql);
$statusnumrows = mysqli_num_rows($query);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$user1 = $row["user1"];
$user2 = $row["user2"];
$accepted = $row["accepted"];
$statusid = $row["id"];
$account_name = $row["account_name"];
$author = $row["author"];
$postdate = $row["postdate"];
$postdate = strftime("%b %d, %Y %I:%M %p");
$data = $row["data"];
$data = nl2br($data);
$data = str_replace("&","&",$data);
$data = stripslashes($data);
$statusDeleteButton = '';
if($author == $log_username || $account_name == $log_username ){
$statusDeleteButton = '<span id="sdb_'.$statusid.'">delete status</span> ';
}
$feedlist .= '<div id="status_'.$statusid.'" class="flipwrapper pin">
<div class="picture">
<header class="img-btm">
'.$postdate.'</b><br />
20 cmts 255 likes '.$statusDeleteButton.'
</header>
<img id="bound" src="'.$data.'"/></div></div>';
}
?>
You definitely don't want a UNION here, but a subquery, more or less like this:
SELECT * FROM status
WHERE author in (
SELECT whateverfieldshouldmapfromfriendstoauthor FROM friends
WHERE user1='$user' AND accepted='1' OR user2='$user' AND accepted='1'
) AND type='a'
And some general tips:
developing your queries straight in your scripting language (in this case php) is a very bad idea. Use a tool that allows you to develop queries, run them and inspect the result sets. There are tons of those, like MySQL's own Workbench and Squirrel SQL
be very careful about SQL injection problems (if your $user variable is provided by the request, you are). The best way to avoid SQL injection problems is by using parameterized queries.

Trouble creating MySQL query in Symfony containing JOIN and RAND()

How do I do this:
SELECT t.id
FROM table t
JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table)
AS tt
ON t.id >= tt.maxid
LIMIT 1
in Symfony? (I know how to do basic stuff, but this is too much.
$connection = Doctrine_Manager::getConnection()->getDbh();
won't work... Try this:
$connection = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
Then:
$stmt = $connection->query('SELECT * FROM some_table');
$stmt->execute();
$result = $stmt->fetchAll();
$connection = Doctrine_Manager::getConnection()->getDbh();
$result = $connection->query('SELECT ...');