Codeigniter Active Record with nested "SELECT WHERE" - php

I was wondering if there was any way in Active Record to create a query with nested WHERE cases like:
SELECT * FROM Users WHERE FirstName = 'John' AND (LastName = 'Smith' OR LastName = 'Jones');

Yes you can use where() function
$this->db->select('*');
$this->db->from('Users ');
$this->db->where("FirstName = 'John'");
$this->db->where(" (LastName = 'Smith' OR LastName = 'Jones') ");
$result=$this->db->get();
Active Record

You need to pass the WHERE clause in order to do this.
$this->db->where("FirstName = 'John' AND (LastName = 'Smith' OR LastName = 'Jones')");

Related

How to use php variables in mysql query while php variable contains mysql query?

How can I implement something like this in mysql?
$query1 = "SELECT id FROM table WHERE username = 'John'";
$query2 = "SELECT id FROM table WHERE username= 'Parsa'";
$query = "SELECT * FROM table WHERE id BETWEEN $query1 AND $query2";
$result = mysql_query($query) or die('Query faild'.mysql_error());
$myrecord = mysql_fetch_assoc($result);
Try this
$query1 ="SELECT GROUP_CONCAT(id) FROM table WHERE firstname in('John','Parsa')";
$query = "SELECT * FROM table WHERE id IN ($query1)";
you have two identical queries , you could just have one . and use IN , not BETWEEN.
You can put those 3 queries in to one query:
$query = "SELECT * FROM table WHERE id
BETWEEN
( SELECT id FROM table WHERE firstname = 'John' GROUP BY id )
AND
( SELECT id FROM table WHERE firstname = 'Parsa' GROUP BY id )
";
although your query doesn't mean anything; you need "()" for subqueries to work.
$query1 = "(SELECT id FROM table WHERE username = 'John')";
$query2 = "(SELECT id FROM table WHERE username= 'Parsa')";
$query = "SELECT * FROM table WHERE id BETWEEN $query1 AND $query2";
u can use a subselection:
SELECT * FROM table WHERE id BETWEEN ($query1) AND ($query2)
But be careful: The Subselection result must be an Integer.

MySQL Union Losing Table Names

I have a MySQL query where I am trying to search 2 tables simultaneously. This is for an autocomplete search box that searches for regular clients and business clients. Here is the code:
$query = mysql_query("SELECT * FROM clients WHERE lastname LIKE '$q%' AND agentid = '$agentid'
UNION
SELECT * FROM busclients WHERE busname LIKE '$q%' AND agentid = '$agentid'")or die(mysql_error());
if($query) {
while ($result = mysql_fetch_array($query)) {
$busname = $result['busname'];
print_r($result);
if(isset($busname)){
$description['id'] = 'viewbusiness.php?id=' . $result['ID'];
$description['value'] = $busname ;
array_push($return_arr,$description);
}
else
{
$description['id'] = 'viewclient.php?id=' .$result['ID'];
$description['value'] = $result['lastname'] . ", " . $result['firstname'] ;
array_push($return_arr,$description);
}
}
}
The problem is that the business clients get assigned the table names from the regular clients, so the code never uses the if(isset($busname)) because busname becomes lastname instead, and directs you to the veiwclient page.
SELECT
a.lastname ,
b.busname
FROM clients as a
INNER JOIN
busclients as b
on b.agent_id = a.agent_id
WHERE a.agent_id = $agent_id
AND (a.lastname LIKE '$q%' OR b.busname LIKE '$q%')
By specifically selecting the column names you want from that table, and selecting a blank string for the others, I believe you can get the results you're looking for using something like this:
SELECT firstname, lastname, '' AS busname FROM clients WHERE ... UNION SELECT '' AS firstname, '' AS lastname, busname FROM busclients WHERE ...

How to add a second query as a condition?

Please see my query below. Right now its look for system_id from contacts where system_id = '$sid' but i want the query to ALSO look for friend_id from contacts where system_id = '$sid'
$tre = mysql_query("SELECT System_id, Full_name FROM accounts
WHERE Full_name LIKE '". mysql_real_escape_string($_GET['q'])."%' LIMIT 5");
while($re=mysql_fetch_array($tre))
{
$qry=mysql_query("SELECT System_id FROM contacts WHERE
System_id='". $sid ."' AND Friend_id='". $re['System_id'] ."'");
if(mysql_num_rows($qry)>0){
if($sid!=$re['user_id']){
$obx['id']=$re['System_id'];
$obx['name']=$re['Full_name'];
$arr[]=$obx;
}
}
How do i tweak it?
Thanks!
Update:
Upon looking up some of the comments below i structured this query that works as expected:
SELECT DISTINCT contacts.friend_id, accounts.full_name,
accounts.system_id
FROM contacts, accounts
WHERE (contacts.system_id = '$sid' AND contacts.friend_id
= accounts.system_id) OR (contacts.friend_id = '$sid'
AND contacts.system_id = accounts.system_id)
The only problem is how do i change the SELECT query from this:
$tre = mysql_query("SELECT System_id, Full_name FROM accounts
WHERE Full_name LIKE '". mysql_real_escape_string($_GET['q'])."%' LIMIT 5");
To $tre:
SELECT DISTINCT contacts.friend_id, accounts.full_name,
accounts.system_id
FROM contacts, accounts
WHERE (contacts.system_id = '$sid' AND contacts.friend_id
= accounts.system_id) OR (contacts.friend_id = '$sid'
AND contacts.system_id = accounts.system_id)

how to select items that concatenation of two rows is like input

i have mysql table, users: (id, first_name, last_name, ....)
i'd like to do something like this pseudo query
SELECT * FROM users WHERE first_name.' '.last_name = 'john doe' LIMIT 10")
I Want to do this cause i have lots of trouble spliting the string (then i don't know in what order is user typing'
This is my current, not working very good
$phrase = explode(' ',$term);
$last_name = '';
if($phrase[1] != '')
$last_name= " OR last_name LIKE '%".$phrase[1]."%'";
$qstring = "SELECT usuarios.first_name,usuarios.last_name,
usuarios.id as id
FROM usuarios
WHERE first_name LIKE '%".$phrase[0]."%' OR last_name LIKE '%".$phrase[0]."%' $last_name LIMIT 5";
Any suggestion to achieve this (by concatenating at query or spliting at php) would be very apreciated
You can concatenate in a MySQL query using CONCAT:
SELECT * FROM users WHERE CONCAT(first_name,' ',last_name) = 'john doe' LIMIT 10
In your code this would become:
SELECT * FROM usuarios WHERE CONCAT(first_name,' ',last_name) LIKE '%{$phrase[0]}%' LIMIT 5
Something like this?
SELECT first_name, last_name, id
FROM usuarios
WHERE CONCAT(first_name, last_name) LIKE '%$phrase[0]%' LIMIT 5

join 2 fields in mysql to search both at the same time

I am trying to search the field firstname and lastname for a keyword
$q1 = strtolower($_GET["q"]);
$q=str_replace(" ","%",$q1);
$sql = "select DISTINCT users.*, user_id FROM users WHERE $email_filter
firstname LIKE '%$q%' OR lastname LIKE '%$q%' ORDER BY lastname";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) { echo $results }
this is what I have so far, issue is if you use John Doe as an example once you type John it finds it, doe it finds it, but john doe ... no results
I recommend that you bind the variables. You are exposed to sql injections otherwise.
$stmt = $mysqli->prepare("select * from users where firstname like ? AND lastname like ?");
$stmt->bind_param('ss', $firstname,$lastname);
Something like
SELECT * FROM users where CONCAT(firstname, ' ', lastname) like '%$q%'
Or
SELECT * FROM users where CONCAT_WS(' ', firstname, lastname) like '%$q%'
And if reversing is desirable, try this:
SELECT * FROM users where CONCAT_WS(' ', firstname, lastname) like '%$q%'
or CONCAT_WS(' ', lastname, firstname) like '%$q%'
(that is, if searching for "A B" should return "A B" as well as "B A")
you have to split your query string and search for each terms
$query_terms = explode(" ", $q1);
$conditions = ''
foreach($query_terms as $term){
$conditions = $conditions.' firstname LIKE "%'.$term.'%" OR lastname LIKE "%'.$term.'%"';
}
$sql = "select DISTINCT users.*, user_id FROM users WHERE $email_filter $conditions ORDER BY lastname";

Categories