How to select only value greater than 0? - php

In my query I want to discard the values equals to 0, actually this is my query:
$query = $this->db->select('GroupID')
->group_by('GroupID')
->from('ea_appointments')
->where('id_users_provider', $record_id)
->get()->result_array();
how you can see this query return only the GroupID value not equals so if I've:
0 - 0 - 1 - 1 - 2
(as GroupID).
I get only:
0 - 1 - 2
now I want to get only the value greater than 0, so thr query should be return this:
1 - 2
how I can achieve that in CodeIgniter?

just add a where statement for the GroupID and include the > symbol at the end of the column name like so:
$query = $this->db->select('GroupID')
->group_by('GroupID')
->from('ea_appointments')
->where('id_users_provider', $record_id)
->where('GroupID >', 0)
->get()->result_array();

Related

Laravel Query how to check if column starts with 0

I have a CRUD application with a Registration table and a Category table. In the RegistrationController, I use a query with Category, so I have made another query. I struggled with checking if every other gender_id has a cte_from that starts with 0. The cte_gender_id has 1, 2, or 3. 1 = man, 2 = women 3 = undetermined and nd cte_from are age ranges.
So in the database: cte_gender_id is 1 and cte_from is 0
then anther row cte_gender_id is 1 and cte_from is 25
then another cte_gender_id is 1 and 35
and so on but with gender_id 2 and 3.
RegistrationController
$gender_ids = ['1', '2', '3'];
foreach ($gender_ids as $gender_id) {
$category = Categorie::where('cte_distance_id', $distance_id)
->where('cte_gender_id', $gender_id)
->where('cte_from',)
->first();
if (is_null($category)) {
return back()->with("errorMessage", "Category not found");
}
}
So I want if, for example, where gender_id is 1 and cte_from doesn't start with 0, it already doesn't go through.
You can use WHERE cte_from LIKE '0%' to test if a string starts with 0. In this query, % is used for a wildcard.
Or in Laravel query builder:
->where('cte_from', 'LIKE', '0%')
// Or if it doesn't start with a 0
->where('cte_from', 'NOT LIKE', '0%')

How to using if statement in mysql

i want to minus 1 (-1) value from durasi_pre_u if durasi_pre_u have basic value bigger then 0 and update Premium to Member when durasi_pre_u have value = 0.
here what i try
UPDATE user
SET durasi_pre_u = IF(durasi_pre_u > 0, durasi_pre_u - 1, durasi_pre_u),
pangkat_u = IF(durasi_pre_u <> 1 AND pangkat_u = 'Premium', pangkat_u = 'Member', pangkat_u)
this code working -1 durasi_pre_u but not working change Premium to Member
i try to follow tutorial from this site https://www.w3resource.com/mysql/control-flow-functions/if-function.php
You have an error in your query, firstly you only want to change the value of pangkat_u when the current value of durasi_pre_u is 1 (so it is about to change to 0) so you need to change the <> to =. Secondly you have pangkat_u = 'Member' as the new value, which is treated as a boolean expression (i.e. a value of 1 or 0) by MySQL. What you actually want is just 'Member'. So your query should be:
UPDATE user
SET durasi_pre_u = IF(durasi_pre_u > 0, durasi_pre_u - 1, durasi_pre_u),
pangkat_u = IF(durasi_pre_u = 1 AND pangkat_u = 'Premium', 'Member', pangkat_u)
In If function, you only need to specify the values to be set in case of true or false. Dont specify the field name = value (pangkat_u = 'Member')
Use the following :
UPDATE user
SET durasi_pre_u = IF(durasi_pre_u > 0, durasi_pre_u - 1, durasi_pre_u),
pangkat_u = IF(durasi_pre_u <> 1 AND pangkat_u = 'Premium', 'Member', pangkat_u)

how can I get row number via php/mysqli

id state
1 1
2 0
5 1
4 0
7 1
I want first remove all state=0 form my result. and then return row number of target record.
for example for id='7' it must return me 3
how can I do it with mysqli/php?
this is false but something like this:
function getLogs($itime = 0,$count = null)
{
$conn = $this->connectDB();
$sql = "SELECT num_rows() FROM Content Where id='22' and $state=0 ORDER BY id ASC";
$rows = mysqli_fetch_all($conn->query($sql), MYSQLI_ASSOC);
$this->disconnectDB($conn);
return num_rows();
}
This is probably simpler and you can replace 22 with a variable.
SELECT COUNT(id) FROM Content WHERE id <= 22 AND state != 0
In your example you put 22 in quotes, but your id isn't a string is it? Plus in addition to the comment above about $state = 0, it should be state not $state

MySQL Count in PHP while loop only returns one result then Null

Ok, so I have some MySQL tables as follows:
Buildings
Building-ID Building-Name
===========----=============
1 Building-1
2 Building-2
3 Building-3
4 Building-4
Building-1
Mroom State
=====----======
1 Booked
2 Empty
3 Empty
4 Empty
Building-2
Mroom State
=====----======
1 Booked
2 Empty
3 Empty
4 Empty
And a query in PHP as follows (Ignore the hard coded while, I've simplified the code a bit):
$sql = "select * from Buildings";
$result = mysql_query ($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$building[] = $row['ward_name'];
}
$v1 = 0;
while ($v1 < 4)
{
$sql = "SELECT COUNT(*) FROM `$building[$v1]` WHERE state = 'Empty'";
$result = mysql_query($sql) or die(mysql_error());
$count = mysql_result($result, 00);
var_dump($count[$v1]);
$v1 = $v1 + 1;
}
To my way of thinking this should create an array of the buildings contained in the "Buildings" table, start a loop, load the building name from the array and provide a row count for the table of how many rows contain "Empty" in the state column. What it actually does is provide a count for the first table and then provides "NULL" for the rest.
I'd appreciate any help you can give me.
Cheers!
What about changing your data model?
Table buldings can be kept as is:
Buildings
Building-ID Building-Name
===========----=============
1 Building-1
2 Building-2
3 Building-3
4 Building-4
New table:
Rooms
Building-ID Mroom State
===========-=====-=====
1 1 1
1 2 0
2 1 0
State 0 = Empty, State 1 = Booked
Then use a join with group by:
select count(*) from buildings b inner join rooms r on r.bid = b.id where r.state = 0 group by b.id;
Then you will get a row for each building with the count of empty rooms. You won't need a table for each building.
This does noit make sense:
$count = mysql_result($result, 00);
var_dump($count[$v1]);
you mean to write:
$count[$v1] = mysql_result($result, 00);
var_dump($count[$v1]);
Also do not use several tables with names matching columns of other tables.
You can use one table with a primary key that spans two columns instead, for example create primary key on($buildingid,$roomid)
so that the table has columns $buildingid,$roomid, and $state.
mysql_result() returns a string, not an array.
Modify the code and check that now it works as expected.
var_dump($count);

SQL query results returned, even if exact match not found

I hope this question isn't redundant. What I am trying to accomplish is have a user select a bunch of checkboxes on a page and return the closest matching records if there are no matching rows. For example:
A person checks off [x]Apples [x]Oranges [x]Pears [x]Bananas
But the table looks like this:
Apples Oranges Pears Bananas
1 1 1 null
1 1 null 1
1 1 null null
(Obviously I missed the id column here, but you get the point I think.) So, the desired result is to have those three rows still be returned in order of most matches, so pretty much the order they are in now. I'm just not sure what the best approach to take on something like this. I've considered a full text search, the levenshtein function, but I really like the idea of returning the exact match if it exists. No need for you to go at length with code if not needed. I'm just hoping to be sent in the right direction. I HAVE seen other questions sort of like this, but I still am unsure about which way to go.
Thanks!
Write a query that adds up the number of columns that matched, and sorts the rows by this total. E.g.
SELECT *
FROM mytable
ORDER BY COALESCE(Apples, 0) = $apples + COALESCE(Oranges, 0) = $oranges + ... DESC
It's easy to sort by a score...
SELECT fb.ID, fb.Apples, fb.Oranges, fb.Pears, fb.Bananas
FROM FruitBasket fb
ORDER BY
CASE WHEN #Apples = fb.Apples THEN 1 ELSE 0 END
+ CASE WHEN #Oranges = fb.Oranges THEN 1 ELSE 0 END
+ CASE WHEN #Pears = fb.Pears THEN 1 ELSE 0 END
+ CASE WHEN #Bananas = fb.Bananas THEN 1 ELSE 0 END
DESC, ID
However, this leads to a table-scan (even with TOP). The last record may be a better match than the records found so far, so every record must be read.
You could consider a tagging system, like this
Content --< ContentTag >-- Tag
Which would be queried this way:
SELECT ContentID
FROM ContentTag
WHERE TagID in (334, 338, 342)
GROUP BY ContentID
ORDER BY COUNT(DISTINCT TagID) desc
An index on ContentTag.TagId would be used by this query.
This is fairly simple, but you can just use IFNULL() (MySQL, or your DB's equivalent) to return a sum of matches and use that in your ORDER BY
// columns and weighting score
$types = array("oranges"=>1, "apples"=>1, "bananas"=>1, "pears"=>1);
$where = array();
// loop through the columns
foreach ($types as $key=>&$weight){
// if there is a match in $_REQUEST at it to $where and increase the weight
if (isset($_REQUEST[$key])){
$where[] = $key . " = 1";
$weight = 2;
}
}
// build the WHERE clause
$where_str = (count($where)>0)? "WHERE " . implode(" OR ", $where) : "";
// build the SQL - non-null matches from the WHERE will be weighted higher
$sql = "SELECT apples, oranges, pears, bananas, ";
foreach ($types as $key=>$weight){
$sql .= "IFNULL({$key}, 0, {$weight}) + ";
}
$sql .= "0 AS score FROM `table` {$where_str} ORDER BY score DESC";
Assuming that "oranges" and "apples" are selection, your SQL will be:
SELECT apples, oranges, pears, bananas,
IFNULL(apples, 0, 2) + IFNULL(oranges, 0, 2) + IFNULL(pears, 0, 1) + IFNULL(bananas, 0, 1) + 0 AS score
FROM `table`
WHERE oranges = 1 OR apples = 1
ORDER BY score DESC
Order descending by the sum of checkbox/data matches
SELECT * FROM table
ORDER BY (COALESE(Apple,0) * #apple) + (COALESE(Orange,0) * #orange) ..... DESC
where #apple / #orange represents users selection: 1 = checked, 0 = unchecked

Categories