How to use AND in JOIN the Codeigniter way - mysql

How can I transform this MySQL query into Codeigniter query?
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON
user_category_subscriptions.category_id = categories.category_id
and user_category_subscriptions.user_id =1

You need to place the AND part inside Codeigniter's join()
$query = $this->db ->select('t1.*')
->join('user_category_subscriptions t2', 't1.category_id =t2.category_id AND t2.user_id =1','left')
->get('categories t1');
return ($query->num_rows())?$query->result():false;
with this line after the query you can double-check if the query was generated correctly:
echo $this->db->last_query();die;
more about CI 2.x Active Record Class and alternatively CI 3.x Query Builder Class

According to the documentation here:
$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->email;
}
echo 'Total Results: ' . $query->num_rows();
ORM:
If you would like to use an ORM, you could follow the advice given on this StackOverflow Link

Related

Codeigniter - how to delete row on inner join? [duplicate]

I have a problem with my query and I need to join two tables from different databases now my problem is how can I execute my query. I got my syntax format from here
Please visit first this link so you could understand why my SQL syntax is like this http://www.x-developer.com/php-scripts/sql-connecting-multiple-databases-in-a-single-query
Im using CodeIgniter and here is an Idea of what my query looks like: Notice the way I'm selecting my columns: DATABASE_NAME.TABLE_NAME.COLUMN_NAME
$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);
$SELECT = "SELECT $ACCOUNTS.BALANCES_TABLE.IDNO, $ACCOUNTS.BALANCES_TABLE.balance";
$FROM = "FROM $ACCOUNTS.BALANCES_TABLE";
$WHERE = "$ACCOUNTS.BALANCES_TABLE.IDNO IN (SELECT $ENROLLEES.ENROLLEES_TABLE.IDNO FROM $ENROLLEES.ENROLLEES_TABLE)";
$SQL = $SELECT ." ". $FROM ." ". $WHERE;
MAIN PROBLEM: How to Execute my query?
If we do like this in codeIgniter:
$ENROLLEES->query($SQL); or $ACCOUNTS->query($SQL);
How can I execute my query that Im having multiple databases? What will I provide here[database]->query($SQL); ?
$sql="Select * from my_table where 1";
$query = $this->db->query($SQL);
return $query->result_array();
If the databases share server, have a login that has priveleges to both of the databases, and simply have a query run similiar to:
$query = $this->db->query("
SELECT t1.*, t2.id
FROM `database1`.`table1` AS t1, `database2`.`table2` AS t2
");
Otherwise I think you might have to run the 2 queries separately and fix the logic afterwards.
I can see what #Þaw mentioned :
$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);
CodeIgniter supports multiple databases. You need to keep both database reference in separate variable as you did above. So far you are right/correct.
Next you need to use them as below:
$ENROLLEES->query();
$ENROLLEES->result();
and
$ACCOUNTS->query();
$ACCOUNTS->result();
Instead of using
$this->db->query();
$this->db->result();
See this for reference:
http://ellislab.com/codeigniter/user-guide/database/connecting.html
http://www.bsourcecode.com/codeigniter/codeigniter-select-query/
$query = $this->db->query("select * from tbl_user");
OR
$query = $this->db->select("*");
$this->db->from('table_name');
$query=$this->db->get();
return $this->db->select('(CASE
enter code hereWHEN orderdetails.ProductID = 0 THEN dealmaster.deal_name
WHEN orderdetails.DealID = 0 THEN products.name
END) as product_name')
$this->db->select('id, name, price, author, category, language, ISBN, publish_date');
$this->db->from('tbl_books');

How to get variables from MSQL query with WHERE IN clause

I have a couple of MySQL tables where I run a query on like this:
$sql = "
SELECT my_item
FROM t1
, t2
WHERE t1.id='$id'
AND t2.spec IN (208, 606, 645)
AND t1.spec = t2.spec
";
Note I am using the WHERE IN.
Next I run a query and use WHILE to try to get the results:
$retval = mysql_query($sql) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem = $row['my_item'];
echo "My item is $myitem<br />\n";
}
This prints three results, each with a different value for $myitem, based on the three options from the IN clause in the SELECT statement at the beginning.
How can I extract and store each of these three values in a separate variable each?
Thank you!
use join
SELECT my_item FROM t1 join t2
on t1.spec=t2.spec
WHERE t1.id='$id'
AND t2.spec IN (208, 606, 645)
or create array
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem[] = $row['my_item'];
}
use this array likt that :-
foreach( $myitem as $myitems){
echo "My item is $myitems<br />\n";
}
or use indexing
echo "My item is $myitems[0]";
You can store the $row['my_item'] in an array.
Refer PHP arrays

Why is this wrong in joomla?

using joomla with k2 I am trying to call from my database the category that is assigned with my item title and I use this code.In order to achieve this. But something is wrong. I do get the title but I am not getting the category name. Below is the code that I am using to get it:
?php
$url= $_SERVER['REQUEST_URI'];
$data = parse_url($url);
$number = basename($data['path'], '.html');
$needle="-";
$number1=substr($number, 0, strpos($number, $needle));
?>
<?php
$db =& JFactory::getDBO();
$db->setQuery('SELECT title FROM #__k2_items WHERE id="'.$number1.'"');
$databaseTitle = $db->loadResult();
$db->setQuery('SELECT catid FROM #__k2_items WHERE id="'.$number1.'"');
$databaseCatid= $db->loadResult();
$db->setQuery('SELECT #__k2_categories.name FROM #__k2_categories INNER JOIN #__k2_items ON #__k2_categories.id = #__k2_items.catid WHERE #__k2_items.catid ="$databaseCatid" LIMIT 1');
$databaseNamecat= $db->loadResult();
?>
<h2>Submit a Charter Request for <?php echo $databaseTitle." from port ".$databaseNamecat; ?></h2>
because you are enclosing a variable between double quotes.
try this
$db->setQuery("SELECT #__k2_categories.name FROM #__k2_categories INNER JOIN #__k2_items ON #__k2_categories.id = #__k2_items.catid WHERE #__k2_items.catid ='".$databaseCatid."' LIMIT 1 ");

Using DISTINCT to filter duplicates?

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

mysql unions with joomla

How do I do mysql UNIONS with joomla 2.5:
$query = parent::getListQuery();
$query
->select('*')
->from('#__game_types')
->where('published = 1')
->order('price ASC')
->union('ALL')
->select('*')
->from('#__dates')
I know union is not a method but I was just trying to show what I'd like to do.
according to my knowledge it's not in the Joomla doc too. So what you can do is execute the query the other way like shown in the example below.
$query = "
SELECT *
FROM . . . ";
$db->setQuery($query);
$row = $db->loadObjectList();