Multiple Like clause CodeIgniter - php

I'm trying to use multiple 'Like' to look for matches in more than one column.
PHP & mysql:
$area = $this->session->userdata('area');
if($area == 'inbox'){
$this->db->where('receiver',$user);
$this->db->where('receiver_deleted !=','yes');
}elseif($area == 'sent'){
$this->db->where('sender',$user);
$this->db->where('sender_deleted !=','yes');
}
$this->db->like('sender',$k);
$this->db->or_like('msg',$k);
$this->db->from('messages');
$this->db->join('users','users.username = messages.sender','inner');
$this->db->order_by('read','no');
$sql = $this->db->get();
if($sql->num_rows > 0){
return $sql->result();
}else{
echo "failed!";
}
I've also tried:
$this->db->like('sender',$k);
$this->db->like('msg',$k);
the first one nothing happens. The second one only one is executed, in this case the first like. I cannot get both to work at the same time.
Any help will be appreciated,
Mike

for this, you should use Grouping with where clause.
$area = $this->session->userdata('area');
if($area == 'inbox'){
$this->db->where('receiver',$user);
$this->db->where('receiver_deleted !=','yes');
}elseif($area == 'sent'){
$this->db->where('sender',$user);
$this->db->where('sender_deleted !=','yes');
}
$this->db->group_start(); //group start
$this->db->like('sender',$k);
$this->db->or_like('msg',$k);
$this->db->group_end(); //group ed

or_like will produce an OR between the two likes. You can pass an array to like to put multiple with an AND between them.
Have you tried doing:
$this->db->like(array('sender' => $k, 'msg' => $k));

This will search multiple column with OR in between
$this->db->or_like(array('sender' => $k, 'msg' => $k));/* LIKE OR LIKE */

Use this:
$this->db->or_like('location',$this->input->post('searchtext'));
$this->db->or_like('title',$this->input->post('searchtext'));
and you will get exact you want.

You could do something like this:
$this->db->get_where('tablename',$whereclause);
I have the same problem and it worked.

Related

laravel eloquent - check if all values of array in table

I have a table options and I have an array of strings ["value1", "value2", "value3"].
What I'd like to do is check if all of the values within the array are present in the table.
I've tried whereIn but I think it checks if any values exist in the table.
This is what I have done currently:
$v = ["value1", "value2", "value3"];
$options = Options::whereIn('value', $v)->get();
if ($options->count() != count($v)) {
//something must be missing
}
This works, but I wonder if there is a better way? The table has millions of records so I'd like to do only 1 query if possible.
Thanks!
The answer in the comments by justcarty is technically correct, but you can reduce the load by not pulling in the options if you don't intend to use them.
if (Option::whereIn('value', [...])->count() != count([...])) {
//perform action
}
Also note, as justcarty mentioned, this won't work if you have multiple occurrences of a value in your database, but you can get around this by adding DISTINCT clause to your query.
if (Option::distinct(['value'])->whereIn('value', [...])->count() != count([...])) {
//perform action
}
whereIn check specifically for that one value in the arrays.
You can try this:
$search_values = ['value1', 'value2', 'value3'];
$found = true;
foreach ($search_values as $search) {
if (!Search::where('column', $search)->first()) {
$found = false;
}
}
if (!$found) {
// Something must be missing
}

WHERE_IN returns only first match in codeigniter

I am trying to get a list of coupons through ajax when the checkboxes are selected. So everything else is working fine but the query is returning only the first match.
So my query is:
$this->db->from('tbl_coupons');
if($storeids !=''){
$ids = array($storeids);
$this->db->where_in('coupon_store', $ids );
}
$this->db->where('coupon_cat', $catid);
$this->db->where('coupon_status', 'active');
$query = $this->db->get();
if ($query->num_rows() > 0) {
$ds = $query->result_array();}
According to this my SQLquery becomes
SELECT * FROM `tbl_coupons`
WHERE `coupon_store` IN('1,97')
AND `coupon_cat` = '16'
AND `coupon_status` = 'active'
But this query is returning values with coupon_store=1 and no results are coming for coupon_store=97
I checked values for coupon store 97 which exists in that category.
use below way if data exist it will be part of query.
storeids = explode(',',storeids);
$ids = array();
foreach($storeids as $val){
$ids[] = $val;
}
if(!empty($ids)){
$this->db->where_in('coupon_store', $ids );
}
hope it will create proper sql query
The query is mostly correct, except at line 2, where you need to make the change as:
WHERE coupon_store IN('1','97')
everything else remains the same.

Is it possible to count all with where condition in codeiginter?

I am trying to do something like this
$this->db->count_all("grant_money")->where('id',5);
is it possible ?
if there is any another way to do this please let me know.Thanks
I want to do this query in single line code Like I tried above
You can use it like this.
$this->db->where('id',5);
$this->db->from("grant_money");
echo $this->db->count_all_results();
this will show all the count with where condition.
with single line try like this
echo $this->db->where('id',5)->from("grant_money")->count_all_results();
$this->db->where('id',5)->count_all_results("grant_money");
Is it possible to count all with where condition in codeiginter?
YES
count in CI based on condition
$this->db->from('mytable');
$this->db->where('field_name',"comapre_vale");
$this->db->like('filed_name',"any_value");
$count = $this->db->count_all_results();
echo $count;
An Example :
$this->db->from('tbl_ontime_attendance');
$this->db->where('Card_Number',$value['emp_code']);
$this->db->like('In_Time',"03/2018");
$days = $this->db->count_all_results();
echo $days;
this is a simple and very easy in this function i have shown the use of both the like and where clause , change according to your to your need.
Try get_data function like this :
$count_all = $this->db->get_data("select count(1) from grant_money where id = 5");
echo $count_all;
You may want to look at CodeIgniter Documentation:
Docs>Database Reference>Database Builder Class
E.g.
echo $this->db->count_all_results('my_table'); // Produces an integer, like 25
$this->db->like('title', 'match');
$this->db->from('my_table');
echo $this->db->count_all_results(); // Produces an integer, like 17
It accepts "Query Builder restrictors" such as where(), or_where(), like(), or_like(), etc.
HTH
yes you can try this may be this will hepfull:-
public function record_count_with_where($table_name,$column_name,$type)
{
$this->db->select($column_name);
$this->db->where($column_name,$type);
$q=$this->db->get($table_name);
$count=$q->result();
return count($count);
}

as of now it just ignores the if statement and gives them a ticket everytime.php, mysql, If else

Alright so i'm trying to put value in an array and shuffle them to be random, then have it use that random value in a query. I know my code is bad and not to use mysql anymore lets stay off that topic please.
I don't understand why this isn't working I have other things like it that work just fine.
right now it ignores the if statement and gives them a ticket each time.
if(isset($_POST['Submit'])) {
$ticket = array("0","0","0","0","0","0","0","1");
shuffle($ticket);
if ($ticket >= 1) {
echo "You have Found a Shop Ticket!" ;
mysql_query("UPDATE users SET ticket=ticket+1 WHERE username = '".$_SESSION['username']."'")
or die(mysql_error());
} else {
echo "";
}
}
You're checking if the entire array is >= 1, which is obviously TRUE all the time.
Pick a value instead:
$ticket = array_shift($ticket); // do this after you shuffle
try
if (current(shuffle($ticket)) >= 1) {
# yay
} else {
# ney
}
$ticket is an array, not a number.
u could use foreach or array_map to do this.
example:
function foo($n){
if($n >= 1){//do something}
}
$ticket = array("0","0","0","0","0","0","0","1");
shuffle($ticket);
array_map('foo', $ticket);

mysql PHP query question

Ok, i have a problem here...
I am sending values of drop down lists via ajax to this PHP file.
Now I want to search a mysql database using these values, which I have managed to do, BUT, only if I set the values to something...
Take a look:
$query = "SELECT * FROM cars_db WHERE price BETWEEN '$cars_price_from' AND '$cars_price_to' AND year BETWEEN '$cars_year_from' AND '$cars_year_to' AND mileage BETWEEN '$cars_mileage_from' AND '$cars_mileage_to' AND gearbox = '$cars_gearbox' AND fuel = '$cars_fuel'";
now, what if the user doesnt select any "price_from" or "year_from"... The fields are only optional, so if the user doesnt enter any "price from" or "year from", then the user wants ALL cars to show...
Do I have to write a query statement for each case or is there another way?
I do something similar to davethegr8 except I put my conditions in an array and then implode at the end just so I don't have to worry about which conditions got added and whether I need to add extra AND's.
For example:
$sql = "SELECT * FROM car_db";
// an array to hold the conditions
$conditions = array();
// for price
if ($car_price_from > 0 && $car_price_to > $car_price_from) {
$conditions[] = "(price BETWEEN '$cars_price_from' AND '$cars_price_to')";
}
elseif ($car_price_from > 0) {
$conditions[] = "(price >= '$cars_price_from')";
}
elseif ($car_price_to > 0) {
$conditions[] = "(price <= '$cars_price_from')";
}
else {
//nothing
}
// similar for the other variables, building up the $conditions array.
// now append to the existing $sql
if (count($conditions) > 0){
$sql .= 'WHERE ' . implode(' AND ', $conditions);
}
You could simply detect which parameters are missing in your PHP code and fill in a suitable default. eg
if (!isset($cars_mileage_to))
$cars_mileage_to = 500000;
You can build you query, adding the "where" part only if your variables are different from "".
or if you're using mysql 5.x, you can also use subselects:
http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
don't forget to validate the input. It's trivial with firebug, for example, to inject some tasty sql.

Categories