Fetching category name with a INNER JOIN - inner-join

I have a query that returns details of an item. It item belongs to a certain category; hence I have linked the ITEMS table to CATEGORIES table with a foreign key being saved to the ITEMS table.
Now, I want the details of any selected item to also display the category name instead of the foreign key. I have tried the INNER JOIN as follows, but surprisingly still the query displays a foreign key.
Here is my query:
/* Create the prepared statement */
if ($stmt = $mysqli->prepare("SELECT categories.category AS category,
items.id,
items.name,
items.description
FROM items
INNER JOIN categories
ON categories.cat_id = items.cat_id
WHERE items.id='$id'")) {
/* Execute the prepared Statement */
$stmt->execute();
/* Bind results to variables */
$stmt->bind_result($id,$category,$name,$description);
/* fetch values */
while ($rows = $stmt->fetch()) {
...
}
...
}
Out put for category name:
<?php
echo $category;
?>
What could be missing here?

Your binding order is wrong, it should be:
$stmt->bind_result($category, $id, $name, $description);
Your order in the SELECT clause matters, so bind_result can figure out wich column binds to wich variable.

This is way out of my element, but nobody answered it yet so I figured I'd take a shot.
Is it because you are selecting 3 items in your query... category, id, description
Then when you are binding variables you're binding 4... $id, $category, $name, $description
So perhaps what is happening is variable $id is actually the category, and $category is actually the id (which is what you're seeing)

You seem to be fetching 3 items (from your select) to 4 variables, I don't think this is good.

Related

Many to many relation hookup in Delphi

How do I do a many to many (master-master) relation in Delphi, I cannot find an example. Only dblookups and master-detail which I understand.
Like a product can belong to one or more categories. Like this table structure:
Product Table
ProductId, ProductName
CategoryTable
CategoryId, CategoryName
Relation table
ProductId, CategoryId
Ideally if you select a record in the product grid the edit of a product in a detail record is started in the right side of the screen. In here you can edit the product properties an ideally you can select via checkboxes one or more categories in a checkbox group/grid.
How do you hook this up with TTable of TQuery components? Is there a way?
Hope you can help!
Sincerely Edward
Some more explaination:
The goal is like:
master [product grid list] Detail [on selected product]
property **A**
property **B**
property **C**
property **D**
property **Category collection**
Category 1 - checked
Category 2 - unchecked
Category 3 - unchecked
Category 4 - checked
This can be transformed to a simple Master-Detail relation by using a joined query over Relation Table and Category Table (similar like this example):
SELECT * FROM Relation a
JOIN Category b on a.CategoryId = b.CategoryId
WHERE ProductId = :ProductId
In case you want a list of all categories where a separate field indicates if a relation to the product exists, you can use a query like this (example for MSSQL, the new field is named Checked):
SELECT c.*, CASE WHEN r.CategoryId IS NULL THEN 0 ELSE 1 END AS Checked
FROM CATEGORY
LEFT JOIN Relation r ON (c.CategoryId = r.CategoryId) AND (r.ProductId = :ProductId)
ORDER BY c.CategoryId
Note that you have to write the code to add or delete the relation record when you manipulate the check list by yourself.

Best rules to get data with Contain

In CakePHP 3 ORM has changed and I can't find the proper way to select needed data from the database.
In CakePHP 2, I use contain('User.name','User.id'), but In CakePHP 3 this code doesn't work.
So how can I select only id and name from User?
The code:
$query = $data->find()->contain(['Users'])->execute()->fetchAll('assoc');
// I want only user.id and user.name.
$articles = $this->Model->find()
->select(['fields_you_want_from_this_Model'])
->contain(['Assoc_Model' => function($q) {
return $q
->select(['fields_you_want_from_the_associated_model']);
}]);
U must take a look about this page: http://book.cakephp.org/3.0/en/orm/query-builder.html#passing-conditions-to-contain
In certain case you must use autoFields method.
Be carefull with contain when u select few fields in the callable, u always have to select the foreign key also:
When you limit the fields that are fetched from an association, you must ensure that the foreign key columns are selected. Failing to select foreign key fields will cause associated data to not be present in the final result.

Postgres - remove element from jsonb array

I have an array of jsonb elements (jsonb[]), with id and text. To remove an element I could use:
UPDATE "Users" SET chats = array_remove(chats, '{"id": 2, "text": "my message"')
But I want to delete the message just by the id, cause getting the message will cost me another query.
Assuming missing information:
Your table has a PK called user_id.
You want to remove all elements with id = 2 across the whole table.
You don't want to touch other rows.
id is unique within each array of chats.
UPDATE "Users" u
SET chats = array_remove(u.chats, d.chat)
FROM (
SELECT user_id, chat
FROM "Users", unnest(chats) chat
WHERE chat->>'id' = '2'
) d
WHERE d.user_id = u.user_id;
The following explanation matches the extent of provided information in the question:

Counting rows and query with AND with codeigniter

I'm trying to count the number of rows of a DB table that matches some criteria. Now I have the following code:
$q = $this->db->get_where('info', array('city_id'=>$city->id));
$count = $query->num_rows();
In the above code, $count will return the number of rows in 'info' table that can matches city_id of 'info' table with the id of the 'city' table. In 'info' table 'city_id' is a FK.
But here I want to check two conditions, like:
1.Whether it matches the fk(city_id) of info table with the id of 'city' table and
2. Whether it matches another field in the info table(lets say name_id=1);
Is there a way that I can join the two queries with AND?
You can add another condition in second parameter of get_where() function.
$q = $this->db->get_where('info', array('city_id'=>$city->id,'name_id'=>1));

Combining SQL results using LINQ

I have a database of company registrants (for a search/directory functionality). We've added a new table to hold "enhanced" information for registrants that pay for this feature (such as advertisements/additional images/logos etc). Right now the new table just holds the registrants unique identifier, and a few additional fields (paths to images etc). A user can search for users with specific criteria, and the enhanced listings should appear at the top of the list. The results should not show any registrant twice (so if a user has an enhanced listing they should only appear in the top "enhanced listing" area). How can I accomplish this?
Left outer join from the old table to the new table.
Prepend to your query's "order by" "case when new_table.id is null then 1 else 0 end"
So if you had this:
select foo, bar from old_table
order by bar, foo;
You'd have this:
select a.foo, a.bar from old_table a
left join new table b on (a.customer_id = b.customer_id)
order by
case when new_table.customer_id is null then 1 else 0 end,
bar, foo;
Edit: I left out the "left" from the outer join in the code.
If you are using LINQtoSQL and the designer-generated entities, you should have an entity set of related information on your registrant entity -- assuming you have set up the proper foreign key relationship. If you added this later you may need to add this by hand (see here) or delete/re-add your entities to the designer for it to pick up the new relationship. Then your query would be something like:
var registrants = db.Registrants.Where( ... selection criteria here ... );
registrants = registrants.OrderByDescending( r => r.EnhancedData.Count() )
.ThenBy( r => r.Name ); // or normal sort order
Presumably count will be either 0 or 1 so this should put the ones with enhanced data at the top of your result.

Resources