Codeigniter mysql where not equal to query - mysql

Mysql codeigniter query is not working properly.
Suppose if mysql table looks like this:
user_id|user_name
1|john
2|alex
3|sam
Here user_name is unique
The following query should return false if user_name=john and user_id=1 and true if say user_name=john and user_id=2.
$this->db->get_where('user', array('user_name' => $name,'user_id !=' => $userid));
But it returns true in the case user_name=john and user_id=1.
Can anyone suggest me an alternative way of querying not equal to.
print($this->db->last_query()) gives:
SELECT * FROM (user) WHERE user_name = 'john' AND user_id != '1'

Why dont you use simple $this->db->query('your query');

Simply try this, Add the desired condition in the where function.
$this -> db -> where('invitee_phone !=', $user_phone);

You can go follwoing way too. It work for me
$total = 5;
$CI = get_instance();
$CI->load->database();
$CI->db->order_by('id','asc');
$topusers = $CI->db->get_where('users',array('user_type != 1 && `status` =' => 1),$total,0);
echo $CI ->db ->last_query();
die;
and if still not work for you can go with #rohit suggest: $this->db->query('your query');

Type 1:
Using ->where("column_name !=",$columnname) is fine for one column.
But if you want to check multi columns, you have to form an array inside where clause.
Like this
$whereArray = array(
"employee_name" => $name,
"employee_id !=" => $id,
);
$this->db->select('*')->from('employee')->where($whereArray);
Type 2:
We can just write exactly what we want inside where.
Like
$thi->db->where(("employee_id =1 AND employee name != 'Gopi') OR designation_name='leader#gopis clan'");
Type 2 is good for working with combining queries, i mean paranthesis "()"

you can follow this code:
$query = $this->db->select('*')->from('employee')->where('user_name', $name)->where('user_id !=', $userid)->get();
$last_query = $this->db->last_query();
$result = $query->result_array();
if you pass $name = 'john' and $userid = '1' then it return empty array.

The problem with using $this->db->query('your query'); is that it is not portable. One of the most important reasons to embrace the query builder methods is so that no matter what database driver you use, CodeIgniter ensures that the syntax is appropriate.
If a bit of discussion was possible, I'd probably like to hear why you need composite primary identifiers in your table and I'd like to see what your table schema looks like. However, I think the time for discussion has long passed.
Effectively, you want to return a boolean result stating the availability of the combination of the username AND the id -- if one is matched, but not both, then true (available).
To achieve this, you will want to search the table for an exact matching row with both qualifying conditions, count the rows, convert that integer to a boolean, then return the opposite value (the syntax is simpler than the explanation).
Consider this clean, direct, and portable one-liner.
return !$this->db->where(['user_name' => $name,'user_id' => $userid])->count_all_results('user');
this will return false if the count is > 0 and true if the count is 0.

Related

Use "Query Builder" to create a function allowing to take the average of values - Symfony

I need help concerning the use of "Query Builder" in Symfony.
I would like to retrieve the values ​​of an attribute (Note) from one of my tables (Avis) in my database. After that, I would like to average all of his scores for display on my site.
For now I have the SQL query which achieves what I want :
SELECT AVG(avis.note) AS notetotal FROM avis
But afterwards, I don't understand what to do, or at least how "Query Builder" works
With the QueryBuilder you can build your queries step by step in a programmatically way, but its actualy only build the DQL wich you can get with $queryBuilder->getDql(). There are some cases where its easier to use the QueryBuilder instead of concatinate a long DQL query string.
There are two possible ways to build the query with the QueryBuilder. But for most cases its recommended to use plain DQL where ever you can, as its more readable.
First with the Expr Class
$queryBuilder = $this->getDoctrine()->getManager()->createQueryBuilder('a');
$queryBuilder->select($queryBuilder->expr()->avg('a.note'))
->from(Avis::class, 'a');
$avg = $queryBuilder->getQuery()->getSingleResult();
// $avg = [1 => (int) AVG]
or without Expr Class
$queryBuilder = $this->getDoctrine()->getManager()->createQueryBuilder('a');
$queryBuilder->select('AVG(a.note) as notetotal')
->from(Avis::class, 'a');
$avg = $queryBuilder->getQuery()->getSingleResult();
// $avg = ['notetotal' => (int) AVG]
The same in DQL
$dql = 'SELECT AVG(a.note) AS notetotal FROM ' . Avis::class . ' a';
$avg = $this->getDoctrine()->getManager()->createQuery($dql)->execute();
// $avg = [0 => ['notetotal' => (int) AVG]]

Codeigniter, Active Record doesn't accept WEEK parameter

It seems that Active Record (Codeigniter) doesn't accept the WEEK parameter and I don't understand why?!
Whern i remove '3', my query works properly!
$this->db->select('WEEK(insere_le,3) AS semaine, COUNT(*) AS nombre')
->from($this->table_name)
->where(array(
'type_anomalie' => "Dérogation",
'YEAR(insere_le)' => $year
))
->group_by('WEEK(insere_le,3)')
->get()
->result_array();
This query, shows the following string when I execute it:
SELECT WEEK(insere_le, `3)` AS semaine, COUNT(*) AS nombre FROM (`aero_anomalie_montage`) WHERE `type_anomalie` = 'Dérogation' AND YEAR(insere_le) = '2014' GROUP BY WEEK(insere_le, `3)`
As you can see it adds an apostrophe before the number 3 and after the parenthesis )
It looks a little confused by your syntax. Why not put them in two different selects (if that's possible...)?
I don't know if this will help, but I found this, it will prevent it from adding the backticks altogether.
$this->db->select() accepts an optional second parameter. If you set
it to FALSE, CodeIgniter will not try to protect your field or table
names with backticks. This is useful if you need a compound select
statement.
http://ellislab.com/codeigniter/user-guide/database/active_record.html
hmm, if you look at active rec class (system/core/database/DB_active_rec.php) you will find this in function select() :
if (is_string($select))
{
$select = explode(',', $select);
}
so what you're select is doing is actually exploding your string into an array like this:
array(
WEEK(insere_le,
3) AS semaine,
COUNT(*) AS nombre
);
and then processing this.
This looks like an oversight from the developers of the active record class, and probably won't be solved by not escaping the values...
On the other hand, it actually checks its a string prior to the above.. so could try this:
$this->db->select(array('WEEK(insere_le,3) AS semaine', 'COUNT(*) AS nombre'))...
and the same with group_by(array('WEEK(insere_le,3)'))...
so end result would be:
$this->db->select(array('WEEK(insere_le,3) AS semaine', 'COUNT(*) AS nombre'))
->from($this->table_name)
->where(array(
'type_anomalie' => "Dérogation",
'YEAR(insere_le)' => $year
))
->group_by(array('WEEK(insere_le,3)'))
->get()
->result_array();
you tried this?:
$this->db->select("WEEK(insere_le,3) AS semaine, COUNT(*) AS nombre", FALSE);

Zend Framework - join query

I build a function
public function getBannedByLogin($commentId)
{
$sql = $this->getDbAdapter()->select()
->from(array('comments' => 'comments'), array())
->join(array('users' => 'qengine_users'),
'comments.bannedBy = users.userId',
array())
->where('commentId = ?', $commentId)
;
$row = $this->fetchRow($sql);
return $row['login'];
}
And there are problems, that does'nt work! :D
Let's I explain you. Column 'bannedBy' from comments returns id of user, who give a ban. I need to join this with table users to load a login field. Where i have mistakes?
I assume the code works in the sense of not throwing an exception. If so, your code is OK, you just specifically tell Zend_Db not to select any columns.
public function getBannedByLogin($commentId)
{
$sql = $this->getDbAdapter()->select()
->from(array('comments' => 'comments'))
->join(array('users' => 'qengine_users'),
'comments.bannedBy = users.userId')
->where('commentId = ?', $commentId)
;
$row = $this->fetchRow($sql);
return $row['login'];
}
The last argument to from() and join() functions is an array of columns you wish to select. If you pass in an empty array, no columns are selected. No argument = select everything. You can, of course, specify only the columns you need too.

What is wrong with this Code Igniter mySQL query?

I have two tables for storing information about a user. One is for authentication, the other is information the user will enter themselves. I am writing a model that will be used when the user interacts with this information. The following method is to return data for display and modification.
I need a query that will return 'email' and 'username' from $accounts_table and * from $profiles_table. I can't seem to get my head around the JOIN syntax though. I understand how joins work, but my queries throw sentax errors.
function get_userdata($id){
$data = array();
$this->db->get_where($this->profiles_table, array('user_id' => $id));
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data= $this->db->get();
return $data;
}
I see a couple of issues:
You should be using $this->db->where(), instead of $this->db->get_where(). get_where() executes the query immediately.
$this->db->get_where('user_id', $id);
Also the first argument of $this->db->join() should only be the table name, excluding the field.
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
And you're returning $data which is just an empty array(). You would need to pass the query results to $data like this:
$data = $record->result_array();
get_where executes the query. So, your join is its own query, which doesn't work.
You need to break get_where into where and from.
Also, in MySQL, you JOIN a table, not a field. If you want that field, add it to the SELECT.
$this->db->select($this->profiles_table.'.*');
$this->db->select($this->accounts_table.'.email,'.$this->accounts_table.'.username');
$this->db->from($this->profiles_table);
$this->db->where('user_id', $id);
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data = $this->db->get();
NOTE: $this->db->get() returns a query object, you need to use result or row to get the data.
I think you've a mistake:
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
First parameter should a table NOT a field: $this->accounts_table.'.email' is wrong IMHO. Or only a typo :)

"No result was found for query although at least one row was expected." Query should display records though in Symfony

I'm trying to retrieve content using two items in the URL. Here is the php/symfony code that should do it:
$em = $this->getDoctrine()->getEntityManager();
$repository = $this->getDoctrine()
->getRepository('ShoutMainBundle:Content');
$query = $repository->createQueryBuilder('p')
->where('p.slug > :slug')
->andWhere('p.subtocontentid > :parent')
->setParameters(array(
'slug' => $slug,
'parent' => $page
))
->getQuery();
$content = $query->getSingleResult();
However, when this code is executed it returns the following error:
No result was found for query although at least one row was expected.
I have done some tests, and the data held in the $slug and $page variables hold the correct information. I have also tested the MySQL query and the query brings up the desired result, which confuses me further.
Have I missed something?
As it was answered here
You are getting this error because you are using the
getSingleResult() method. it generates an Exception if it can't find
even a single result. you can use the getOneOrNullResult() instead
to get a NULL if there isn't any result from the query.
Query#getSingleResult(): Retrieves a single object. If the result
contains more than one object, an NonUniqueResultException is thrown.
If the result contains no objects, an NoResultException is thrown. The
pure/mixed distinction does not apply.
No result was found for query although at least one row was expected.
Another reason could be:
You did this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
return $query->getSingleResult();
Instead of this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
$query->setMaxResults(1);
return $query->getResult();
Don't you want to use "=" instead of ">" ?
If you've got this message because used
$content = $query->getSingleResult();
you can just replace it with the row below
$content = $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) ?? 0;