Codeigniter $query->result() returns strange results - php

This peace of code is driving me crazy for last hour...
I have this model which should return all non active records from DB
$query = $this->db->get($tableName);
echo $this->db->last_query();
var_dump($query->result());
$this->db->last_query() output is
SELECT * FROM `locations` LEFT JOIN `provinces` ON `provinces`.`id_province` = `locations`.`id_province` LEFT JOIN `countries` ON `countries`.`id_country` = `provinces`.`id_country` LEFT JOIN `statuses` ON `statuses`.`id_status` = `locations`.`id_status` WHERE `locations`.`active` = '0' ORDER BY `locations`.`id_location` DESC LIMIT 50
If i run exactsame query in phpmyadmin i get correct results
But when i var_dump data var_dump($query->result()); i get the following results
array (size=50)
0 =>
object(stdClass)[61]
public 'unique_id' => string 'OWYwYjBmNm' (length=10)
public 'active' => string '1' (length=1)
public 'owner_name' => string 'Cleve Greenfelder' (length=17)
1 =>
object(stdClass)[62]
public 'unique_id' => string 'YWY4YmMzMm' (length=10)
public 'active' => string '1' (length=1)
public 'owner_name' => string 'Bradford Hyatt' (length=14)
Why/how this active state get's overwritten from 0 to 1?
IF you need any additional information's, please let me know and i will provide. Thank you!

Once i wrote a question, answer quickly appeared in my head :)
Table Countries has also active field, so this field overwrites active state as enabled. I needed to specified fields and there's name in query in order to get proper results
$fields = 'unique_id, locations.active as active, ....';

Related

Referencing the count in object PHP

I'm trying to reference COUNT(*) from the object below. I grab the date using $the_date = $obj2->the_date as per the below example, but how do I reference count? Of course using COUNT(*) will throw an error.
object(stdClass)[358]
public 'COUNT(*)' => string '36' (length=2)
public 'the_date' => string '2019-08-29' (length=10)
You need to alias the concerned column in the resultset of the query, like:
SELECT the_date, COUNT(*) as cnt FROM ...
Then:
object(stdClass)[358]
public 'cnt' => string '36' (length=2)
public 'the_date' => string '2019-08-29' (length=10)

How to link and display MySQL data from two different tables?

I have two tables named "stats" and "users"
users table has all the typical user data like id,username,password,email(columns)
stats table has id,attack, defense,ostats,gold,food(columns)
I want to display data from these two tables side by side and have the data linked through their IDS
For example,
Rank user_uid ostats attack defense gold
1 Test 10 5 5 100
2 Test2 8 2 6 60
3 Test3 6 5 1 40
Username is from table "users" and the rest of them are from table "stats"
So first I want to know how to link and display the data from the same ID, like Username(user_id=1) and ostats,attack,defense,gold,food(id=1)
Then I want them in order by their "ostats" (I don't have a column named "rank" in any table yet, just don't know how to create the rank using overall stats)
You could do something like (untested)
SELECT u.username, s.overall, s.attack, s.defense, s.gold
FROM stats s JOIN users u on s.user_uid = u.id
ORDER BY s.overall;
Possible solution to ranking:
set #row_number=0;
SELECT (#row_number:=#row_number+1) as rank, u.username, s.overall, s.attack, s.defense, s.gold
FROM stats s JOIN users u on s.user_uid = u.id
ORDER BY s.overall;
Another, horrible looking attempt:
set #row_number = (select count(*) from users) + 1;
select (#row_number:=#row_number-1) as rank, u.username, s.overall from
stats s join users u on s.user_uid = u.id order by s.overall desc;
set #row_number = 0;
Here in PHP code, you have to run it as two queries to set the variable, then run the actual ranking query. This way, the rank variable is always set to 0 when running this. Note that I've used different table and column names, just to simplify things a little. Remember to adjust to your specific needs.
// connect to database
$conn = mysqli_connect("localhost", "user", "password", "database");
// this query will set a variable to 0.
$setSql = "SET #row_number = 0;";
// run the query. This will return a boolean - true or false, depending on whether or not the query ran successfully
$variableSet = mysqli_query($conn, $setSql);
// if the query ran successfully
if($variableSet){
// setup the actual ranking query
$statsSql = "select
(#row_number:=#row_number+1) as rank,
u.id,
u.username,
s.overall
from
mstats s
join
musers u
on
s.muser = u.id
order by
s.overall desc;";
$ranks = mysqli_query($conn, $statsSql);
if(!$ranks){
// dump error from rank query
var_dump($conn->error);
} else {
// dump results as associative array
var_dump($ranks->fetch_all(MYSQLI_ASSOC));
}
} else {
// dump errors from setting variable
var_dump($conn->error);
}
For me, the results dump looks like this:
array (size=3)
0 =>
array (size=4)
'rank' => string '1' (length=1)
'id' => string '2' (length=1)
'username' => string 'Bar' (length=3)
'overall' => string '1000' (length=4)
1 =>
array (size=4)
'rank' => string '2' (length=1)
'id' => string '6' (length=1)
'username' => string 'Tom' (length=3)
'overall' => string '7' (length=1)
2 =>
array (size=4)
'rank' => string '3' (length=1)
'id' => string '1' (length=1)
'username' => string 'Foo' (length=3)
'overall' => string '3' (length=1)

Query with union condition

Does anyone know how can I write a query to get the desired result to be like tools/lift planning/cranimax from this database
resource_category_id category_name parent_category
1 Tools 0
2 product literature 0
3 Terms and Conitions 0
4 crane library 1
5 geniune 1
6 lift planning 1
8 cranimax 6
For this I wrote a query like this which is not completed, for example this is thing am having in my mind if I choose from cranimax it's having a parent_category 6 so it should make union with that row having resource_category_id and that row having parent_category 1 it should repeat until parent category 0 occurs.
$data['breadcrumbs'] = $this->Manito_model->get_breadcrumbs_details($resource_id);
public function get_breadcrumbs_details($resource_id)
{
$query=$this->db->query("select * from resource_category as m WHERE m.resource_category_id = $resource_id union (select * from resource_category where parent_category != 0) as m2 on m.parent_category = m2.resource_parent_category");
return $query->result();
}
i expect my result to be like this
array (size=3)
0 =>
object(stdClass)[35]
public 'resource_category_id' => string '8' (length=1)
public 'category_name' => string 'cranimax' (length=8)
public 'parent_category' => string '6' (length=1)
public 'created_at' => string '2017-11-04 13:59:39' (length=19)
1 =>
object(stdClass)[35]
public 'resource_category_id' => string '6' (length=1)
public 'category_name' => string 'lift planning' (length=8)
public 'parent_category' => string '1' (length=1)
public 'created_at' => string '2017-11-04 13:59:39' (length=19)
2 =>
object(stdClass)[35]
public 'resource_category_id' => string '1' (length=1)
public 'category_name' => string 'Tools' (length=8)
public 'parent_category' => string '0' (length=1)
public 'created_at' => string '2017-11-04 13:59:39' (length=19)
UNION is used to combine the result from multiple SELECT statements into a single result set (ie making it extremely simple: you need to do two select, but you want only one result, then you make a union)
In you situation you don't need a UNION, but a simple JOIN which "complete" your results with other data:
select m.*, m2.category_name AS parent_name FROM resource_category AS m LEFT JOIN resource_category m2 ON m2.resource_category_id = m.resource_parent_category WHERE m.resource_category_id = $resource_id

Woocommerce Select Orders which match multiple meta values

I'm currently working on a plugin which was built for a bakery to email reports about orders. They have since opened another store and now the reports need to be split into separate emails depending on store location.
I have the following sql query:
$sql = "SELECT o.order_item_id, o.order_item_name, o.order_id, po.post_date AS order_date_placed
FROM wp_woocommerce_order_items AS o
LEFT JOIN wp_woocommerce_order_itemmeta AS oi ON o.order_item_id = oi.order_item_id
LEFT JOIN wp_posts AS po ON po.ID = o.order_id
WHERE oi.meta_key='Collection Date'
AND oi.meta_value IN ('16/01/2016','17/01/2016','18/01/2016','19/01/2016','20/01/2016','21/01/2016')
ORDER BY po.post_date ASC, o.order_item_id ASC";
This query returns all orders which are to be collected within a specific date range.
array (size=3)
0 =>
object(stdClass)[593]
public 'order_item_id' => string '19582' (length=5)
public 'order_item_name' => string '10 Chocolate Cupcakes' (length=21)
public 'order_id' => string '15234' (length=5)
public 'order_date_placed' => string '2016-01-14 08:51:31' (length=19)
1 =>
object(stdClass)[592]
public 'order_item_id' => string '19600' (length=5)
public 'order_item_name' => string '10 Chocolate Cupcakes' (length=21)
public 'order_id' => string '15248' (length=5)
public 'order_date_placed' => string '2016-01-14 15:43:08' (length=19)
2 =>
object(stdClass)[591]
public 'order_item_id' => string '19603' (length=5)
public 'order_item_name' => string '10 Chocolate Cupcakes' (length=21)
public 'order_id' => string '15250' (length=5)
public 'order_date_placed' => string '2016-01-14 15:45:25' (length=19)
I now want to pass an additional criteria that will also limit the return data to a specific store location.
I have tried adding the following to the query but this returns null.
WHERE oi.meta_key = 'Pickup Location'
AND oi.meta_value LIKE '%Address 1%'
Only records which are true for both criteria must return.
I do battle to understand why the meta table in wordpress/woocommerce are set up the way they are with so many redundant/duplicate entries.
I'm not sure whether the developer should have used a raw SQL query or whether there is a better solution for this problem.
Any help is much appreciated.
I guess you are looking for this query
SELECT o.order_item_id,
o.order_item_name,
o.order_id,
po.post_date AS order_date_placed
FROM wp_woocommerce_order_items AS o
LEFT JOIN wp_woocommerce_order_itemmeta AS oi
ON ( o.order_item_id = oi.order_item_id
AND oi.meta_key = 'Collection Date'
AND oi.meta_value IN ( '16/01/2016', '17/01/2016','18/01/2016',
'19/01/2016','20/01/2016', '21/01/2016' ) )
OR ( oi.meta_key = 'Pickup Location'
AND oi.meta_value LIKE '%Address 1%' )
LEFT JOIN wp_posts AS po
ON po.id = o.order_id
ORDER BY po.post_date ASC,
o.order_item_id ASC
And move the filter to ON conditions since those belongs to right table

Selecting unique records from mysql with considering only one field

My question may be not reflecting my problem, sorry for that at first. I have a problem , I need to select distinct movie names from a table also selecting its id and other records. But since ids are different for each movies, all the movies are selected(with same name ). Here's the query :
$sql = "
SELECT DISTINCT
movie_id,movie_name
FROM
tbl_current_movies as cm, tbl_movie_hall as mh
WHERE
movie_active = 'active'
AND
cm.hall_id = mh.hall_id
";
$res = $this->db->returnArrayOfObject($sql,$pgin = 'no');
var_dump($res);
And var_dump($res) says :
array
0 =>
object(stdClass)[48]
public 'movie_id' => string '1' (length=1)
public 'movie_name' => string 'MIB' (length=12)
1 =>
object(stdClass)[49]
public 'movie_id' => string '2' (length=1)
public 'movie_name' => string 'Jetuka Pator Dare' (length=17)
2 =>
object(stdClass)[50]
public 'movie_id' => string '3' (length=1)
public 'movie_name' => string 'MIB' (length=12)
So as you can see the movie MIB is showing twice, but I want to get in the results the movies MIB only once !
Change your query to this :
$sql = "SELECT movie_id , movie_name
FROM tbl_current_movies as cm
LEFT JOIN tbl_movie_hall mh ON cm.hall_id = mh.hall_id
WHERE movie_active = 'active'
GROUP BY movie_name
";
You shouldn't join your tables in the WHERE clause, if you're not confortable with the JOINs you can read some of the docs : http://dev.mysql.com/doc/refman/5.0/en/join.html
That should help you understand what they are for.

Categories