I have an issue with getting data of the joined table if I use query().
I did not get the data of product table, how can I solve this using query() without using Active record?
Here is my db table structure
category table
+--------------------------+
| cId | added | category |
+-----+--------+-----------+
| 1 | 1.2.20 | PC |
| 2 | 1.7.20 | electron |
+-----+--------+-----------+
product table
+--------------------------+
| id | cId | cost |
+-----+--------+-----------+
| 1 | 1 | 3000 |
| 1 | 2 | 9000 |
+-----+--------+-----------+
My Model
protected $table = 'category';
public function showProduct()
{
$sql = "SELECT
category.*, COALESCE(SUM(product.cost),0) as price
FROM category
JOIN product
ON product.cId = category.cId
GROUP BY category.cId
";
$this->db->query($sql);
return $this;
}
My Controller
public function index()
{
$result = $this->model->showProduct();
echo "<pre>";
print_r($result->asObject()->paginate(1));
//pagination
$pager = $this->model->showProduct()->pager->links();
}
Result I get
Array
(
[0] => stdClass Object
(
[cId] => 1
[added] => 1.2.20
[category] => PC
)
[1] => stdClass Object
(
[cId] => 2
[added] => 1.7.20
[category] => electron
),
)
You are requested to run this code.
SELECT category.cId,category.added,category.category,product.id,COALESCE(SUM(product.cost),0) as price
FROM category,product
WHERE category.cId=product.cId
GROUP BY category.cId;
If you are using CodeIgniter-4 then you can easily write this using Query Builder Class.
$sql="SELECT category*,product* FROM category INNER JOIN product.cid=category.id WHERE category.id";
I found solution to this by setting this table property within a function.
Model
$protected $table = array("default bd table here");
public function showProduct()
{
$this->table = array('category');
$sql = "SELECT
category.*, COALESCE(SUM(product.cost),0) as price
FROM category
JOIN product
ON product.cId = category.cId
GROUP BY category.cId
";
$this->db->query($sql);
return $this;
}
My Controller
public function index()
{
$result = $this->model->showProduct();
//pagination
$pager = $this->model->showProduct()->pager->links();
}
Related
On terminal, in mysql , running the following query gives this result
mysql> SELECT DISTINCT(city) FROM outlets_data;
+-----------+
| city |
+-----------+
| Paris |
| New York |
| Kolkata |
| Moscow |
| Mumbai |
| Hyderabad |
| Delhi |
| Chennai |
+-----------+
8 rows in set (0.00 sec)
I want to store the names of these cities, in an array, in codeigniter 4 models class file.
Models/DashboardModels.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class DashboardModel extends Model
{
protected $table = 'outlets_data';
protected $primaryKey = 'shop_id';
public function not_defined_yet()
{
$city_names = $this->select('city')->distinct(); // This should be equivalent to "SELECT DISTINCT(city) FROM outlets_data";
return $city_names;
}
}
Controller/Home.php
<?php
namespace App\Controllers;
use App\Models\DashboardModel;
use CodeIgniter\Model;
class Home extends BaseController
{
public function index()
{
$model = new DashboardModel();
$data['undefined'] = $model->not_defined_yet();
echo view('dashboard', $data);
}
}
Views/Dashboard.php
<?php echo "<pre>"; print_r($undefined); echo "</pre>"; ?>
I expect to get names of the cities in output array, but I am getting whole database as associative array.
Your function should be:
public function not_defined_yet()
{
$city_names = $this->select('city')->distinct(); // This should be equivalent to "SELECT DISTINCT(city) FROM outlets_data";
return $this;
}
Then your function be
$data['undefined'] = $model->not_defined_yet()->findAll();
Other way you can do it is loading a new instance of the database object.
public function not_defined_yet()
{
$db = \Config\Database::connect();
$builder = $db->table('outlets_data');
$city_names = $builder->select('city')->distinct();
return $city_names->resultArray();
}
You can even remove the function all together and in your controller do this:
$data['undefined'] = $model->select('city')->distinct()->findAll();
This would get the same exact result.
I have 2 table that want to call in and make another array from it.
The first table is groups
| id | name | type |
1 premium pr
2 basic bs
The second table is sub-groups
| id | group_id | name |
1 1 forever
2 2 short
Actually I want to show the code like this. To have another array function declare as sub-groups
Array (
[id] => 1
[name] => Premium
[type] => pr
)[sub-groups] => Array (
[0] => Array (
[id] => 1
[group_id] => 1
[name] => forever))
I created this PDO sql connection
=================EDITED CODE====================
function getGroups(){
global $conn;
$stmt = $conn->prepare("SELECT * FROM groups");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$groups = $stmt->fetchAll();
foreach($groups as $key => $val){
$stmt = $conn->prepare("SELECT * FROM sub_groups WHERE group_id = {$val['id']}");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$program = $stmt->fetchAll();
foreach($program as $key => $val){
$groups['sub-groups'] = $program;
}
}
return $groups;
}
The code successfully show the groups Premium and Basic, But it's not showing the sub-groups inside the main groups. Did I miss something?
Anyone with help will be nice.
Array keys have to be unique. If you have two columns with the same name, only one of them can appear in the resulting associative array for the rows.
You need to assign an alias to at least one of the columns with the same name so it will show up differently in the results.
SELECT g.name as group_name, sg.group_id, sg.id AS subgroup_id, sg.name AS subgroup_name
FROM groups AS g
LEFT JOIN subgroups AS sg ON sg.group_id = g.id
When you're creating the PHP result, $groups['sub-groups'] needs to be an array. You're overwriting it with a single element each time through the loop.
<?php
function getGroups(){
global $conn;
$groups = [];
$stmt = $conn->prepare("
SELECT g.name as group_name, sg.group_id, sg.id AS subgroup_id, sg.name AS subgroup_name
FROM groups AS g
LEFT JOIN subgroups AS sg ON sg.group_id = g.id");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $stmt->fetch()){
if (!isset($groups[$row['group_name']])) {
$groups[$row['group_name']] = $row;
$groups[$row['group_name']]['sub-groups'] = [$row['subgroup_name']];
} else {
$groups[$row['group_name']]['sub-groups'][] = $row['subgroup_name'];
}
}
return $groups;
}
I got two tables. I want to get all users and their details who are active/banned.
What is laravel eloquent equivalent to this query.
'select * from client_details where user_id IN (select user_id from client_logins where is_active='.$active.')'
Table: client_logins Model clientLogin
+---------+---------+--------------+-------------+-----------+
| id | user_id | username | password | is_active |
+---------+---------+--------------+-------------+-----------+
Table: client_details Model clientDetail
+---------+------+-------+------------------+
| user_id | name | email | mobile | address|
+---------+------+-------+------------------+
Using query builder you could write it as
$clients=DB::table('client_details as c')
->select('c.*')
->join('client_logins as l', 'c.user_id', '=', 'l.user_id')
->where('l.is_active', '=', $active)
->get()
;
Or if have defined has relation for ClientDetails model you can use whereHas filter
class ClientDetails extends Model
{
public function client_logins()
{
return $this->hasMany('App\ClientLogins', 'user_id', 'user_id');
}
}
$clients = ClientDetails::whereHas('client_logins', function ($query) use ($active) {
$query->where('is_active', '=', $active);
})->get();
Say I have a table 'table_name' with two columns like this:
table_name
------------
my_id | data
------|-----
id1 | 312
id1 | 523
id1 | 128
id2 | 239
id2 | 479
id2 | 121
id3 | 639
id3 | 429
id3 | 131
id4 | 473
id4 | 872
id4 | 662
id4 | 174
id4 | 272
I tried around a while and I now found a way to select the ids I want to use:
SELECT DISTINCT my_id from table_name WHERE (my_id REGEXP 'id[234]')
This gives me the ids 'id2', 'id3' and 'id4'. How would I formulate a query that gives me my desired output, based on the selected ids as below?
id2 | id3 | id4
---------------
239 | 639 | 473
479 | 429 | 872
121 | 131 | 662
NaN | NaN | 174
NaN | NaN | 272
If your table really only has those two columns and there is no related data that can be used to order the data column like you have shown, then there is no good way to achieve the ordering you're looking for.
Relational data doesn't have any intrinsic "order" to it, even if you've inserted that data in a particular order or displayed it in a certain way here. If your table really only has those two columns, it will be difficult to match the "first" id2 value with the "first" id3 value and so on to get to your desired output. We could potentially rank them in a query and match them based upon that rank (ascending or descending) or even provide some random order capability, but there is no documented (i.e. reliable) way to get the order that you've provided.
While a table does have a physical order to the underlying bits in storage, and some products allow you to access them via a physical rowid (Oracle), no RDBMS that I know of (including MySql) guarantees the order in which the rows will be returned unless an order by clause is used in your select statement. This is literally by design and is considered a "feature" that came out of E.F. Codd's research.
First make a function that select distinct of the id's
public function get_id_of_table_name() {
$sql = 'SELECT DISTINCT my_id ';
$sql .= 'FROM table_name ';
$query = $this->db->query($sql);
$result = $query->row();
foreach ($result as $key => $value)
{
$result->data = $this->get_data($result->my_id);
}
return ( $query->num_rows() ) ? $result : FALSE;
}
And create the second function that will gather all the data's base on what id's
public function get_data($my_id) {
$params = [];
$sql = 'SELECT data ';
$sql .= 'FROM table_name ';
$sql .= 'WHERE my_id = ? ';
$params[] = $my_id;
$query = $this->db->query($sql, $params);
$result_data = $query->result();
$data = [];
foreach ($result_data as $result)
{
array_push($data, $result->data);
}
return $data;
}
You can put a where clause in the first function if you want.
$sql .= 'WHERE my_id = ? ';
and add the params
$params[] = $my_id;
You can also add parameters my_id as array in the first function so that you can get what id you want to get
$id = ["id2","id3","id4"];
public function get_id_of_table_name($id) {
$params = [];
$sql = 'SELECT DISTINCT my_id ';
$sql .= 'FROM table_name ';
$sql .= 'WHERE 1 ';
foreach ($id as $my_id)
{
$sql .= 'OR (my_id = ?) ';
$params[] = $my_id;
}
$query = $this->db->query($sql, $params);
$result = $query->row();
foreach ($result as $key => $value)
{
$result->data = $this->get_data($result->my_id);
}
return ( $query->num_rows() ) ? $result : FALSE;
}
I need an SELECT with JOIN but have at this moment no idea how to do this. I read already a few tutorials but it does not help me with my problem.
I have 2 tables in 2 databases:
DATABASE A
-> CONTENT
--> | PARTNERID | PAYSITE |
--> | 1 | siteA.com |
--> | 2 | siteA.com |
--> | 3 | siteA.com |
--> | 3 | siteB.com |
DATABASE B
-> WMIDPP
--> | WMID | PARTNERID | PARTNERURL | PAYSITE | ACTIVE
--> | 1 | 1 | AFFLINK 1 | siteA.com | 1
--> | 1 | 2 | AFFLINK 2 | siteA.com | 1
--> | 2 | 1 | AFFLINK 1 | siteA.com | 1
The above tables contains more fields, but with these fields I need to work with.
I know already the variables $WMID and $PAYSITE if I enter the website. When I enter the website, it should be show only the following data:
The complete data from table CONTENT and the field PARTNERURL from table WMIDPP when
CONTENT.PARTNERID = WMIDPP.PARTNERID
and
WMIDPP.WMID = $WMID
and
WMIDPP.PAYISTE = $PAYSITE
but only if
WMIDPP.ACTIVE = 1
Can anybody help with my problem?
Thanks in advance
Torsten
EDIT:
Here a little bit more information about the databases and tables:
Table CONTENT is located in DATABASE A and table WMIDPP is located in DATABASE B.
I access to these databases like this:
$DB_HOST = "localhost";
$DB_NAME1 = "database1";
$DB_NAME2 = "database2";
$DB_USER = "username";
$DB_PASS = "password";
$OPTION = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
try {
$dbAS = new PDO("mysql:host=" . $DB_HOST . ";dbname=" . $DB_NAME1, $DB_USER, $DB_PASS, $OPTION);
$dbEC = new PDO("mysql:host=" . $DB_HOST . ";dbname=" . $DB_NAME2, $DB_USER, $DB_PASS, $OPTION);
}
catch (PDOException $e) { exit("Verbindung fehlgeschlagen! " . $e->getMessage()); }
User has permissions to access to both databases.
I have 2 different databases, because there are 2 different projects. If it not work with these configuration, I can move the table(s) from DATABASE B to DATABASE A - but this should only the worst case option. I prefer a solution to merge the data of the tables in 2 different databases.
You use One PDO connection.
The signon details must allow access to both databases you want to access.
The full 'path' to any column is:
<database name> . <table name> . <column name>.
Here is tested code that joins tables from two separate databases.
Database 1) is called: 'testmysql'
Database 2) is called: 'rags1'
They are just databases i have setup here with similar structured tables on them.
Join two tables from separate databases
/* --------------------------------------------------------------------
* Query testmysql and rags1
*/
$sqlTest = 'SELECT rags1.user.id as RagsRowId,
rags1.user.userid as RagsUserId,
testmysql.customer.id as TestRowId,
testmysql.customer.custid as TestCustId,
testmysql.customer.address as TestCustAddress
FROM testmysql.customer
JOIN rags1.user
ON testmysql.customer.custid = rags1.user.userid
AND testmysql.customer.custid = :testCustId';
$stmt = $dbTest->prepare($sqlTest);
$stmt->bindValue(':testCustId', 'rfv123', PDO::PARAM_STR);
$stmt->execute();
$testResult = $stmt->fetchAll();
$stmt->closeCursor();
echo '<pre>';
print_r($testResult);
echo '<pre>';
Connection Details:
/**
* Two databases :
* 1) testmysql
* 2) rags1
*
* Use the 'database' name that you want to refer to in the queries.
*/
/**
* must have access rights to both db's
*/
// db connection to TestMysql and Rags1
$dsn = 'mysql:host=localhost;dbname=testmysql';
$username = 'rfv123';
$password = 'rfv123';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$dbTest = new PDO($dsn, $username, $password, $options);
$dbTest->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Output:
Array
(
[0] => Array
(
[RagsRowId] => 1
[0] => 1
[RagsUserId] => rfv123
[1] => rfv123
[TestRowId] => 3
[2] => 3
[TestCustId] => rfv123
[3] => rfv123
[TestCustAddress] => 123 Somewhere Street, Cheshire
[4] => 123 Somewhere Street, Cheshire
)
)