unable to sort alphabatically when calling data from db - php

I am trying to sort alphabetically. I am calling data from database. In the table i am storing ID's of Make like Suzuki, Toyota. I have 1 table naming Make in which i am saving Makes like Toyota.
then i am adding into Models with respect to Make like Land Cruiser is a model and its Make is Toyota. i am inserting ID of the Make from Make's table. then on front end, i am converting the ID's back to Make's name. I want to show Makes name alphabetically.
Here what i do
<?php
$SelectMainCats = mysqli_query($con, "SELECT * FROM model");
$S_NO = 0;
while($row=mysqli_fetch_assoc($SelectMainCats)){
$S_NO++;
$getid = $row['id'];
//converting ids to names
$main_make_query = mysqli_query($con,"SELECT * FROM make WHERE id=".$row['make']);
$main_make = mysqli_fetch_assoc($main_make_query);
?>
Front end calling
<td><?php echo $main_make['maker_name'];?></td>

Running a query and looping through the result set to run more queries is almost always the wrong way to SELECT data. You should be using a JOIN to link the two tables, then one query will retrieve all the data, sorted in the order you want.
Based on this data:
Makes
id makerName
1 Ford
2 Suzuki
3 Toyota
Models
id makerId modelName
1 1 Prefect
2 2 Swift
3 3 LandCruiser
4 3 Celica
5 1 Orion
6 2 Splash
7 1 Mondeo
This Query
SELECT b.makerName, a.modelName FROM models a join makes b on a.makerId = b.id order by makerName;
Gives this result
makerName modelName
Ford Prefect
Ford Orion
Ford Mondeo
Suzuki Swift
Suzuki Splash
Toyota LandCruiser
Toyota Celica

Related

Query to join two table and sort the data array using PHP and MySQL

I need one help.I have two table i need to join two table and display them inside user's table.I am explaining my table structure below.
db_summary:
id member_id hit_type device_type
1 20 1 IOS
2 12 2 IOS
3 20 3 Android
4 14 4 Android
5 12 3 IOS
6 14 5 IOS
From the above table the hit_type column value is linked to the following table's type column.
db_hit_type:
id name type
1 Page 1
2 Map 2
3 Gallery 3
4 Phone 4
5 Web 5
From the db_summary table if hit_type=1 means its a page hit which is defined in second table. Here i need to fetch both table data by joining and sort them as per member id to display in following user's ui table.
sl no member page Hit Map Hit Gallery Hit Phone Hit WebHit TOTAL
i need to fill the above table by using the db data.suppose for member id 20 how many nos of page hit,Map hit...... and total nos of hit.I need to fetch all data and sort them as per user's table structure.Please help me.
Use below query to get both table data
SELECT * FROM db_summary AS ds, db_hit_type AS dht WHERE ds.hit_type = dht.type GROUP BY ds.member_id
SELECT dbs.*,dbht.name,dbht.id as dbHitId
FROM db_summary as dbs
LEFT JOIN db_hit_type as dbht
ON dbs.hit_type=dbht.type
ORDER BY dbs.member_id
I don't know how or when you want to view the resulting data, but at some point you will need to run a query counting each type of hit per user from the db_summary table, then updating the user table with the resulting data.
You could do something like this:
$stmt = $db->prepare("SELECT * FROM `db_summary` WHERE `member_id` = :member");
$stmt->bindParam(':member', $memberid);
$stmt->execute();
$hit = array(0,0,0,0,0);
while ($row = $stmt->fetch(PDO::ASSOC))
{
++$hit[$row['hit_type']-1];
}
echo 'Type 1 Hits: ', $hit[0];
echo 'Type 2 Hits: ', $hit[1];
echo 'Type 3 Hits: ', $hit[2];
echo 'Type 4 Hits: ', $hit[3];
echo 'Type 5 Hits: ', $hit[4];
If you need to update all members, you can wrap all of that into a loop that loops through each member id.

MySQL join for CodeIgniter

I have 2 tables. Table kind and table living.
In the table kind, it has id, kind_o & living_id while in living it has id & type.
Example data.
KIND
id kind_o living_id
1 dog 1
2 narra 2
LIVING
id type
1 animal
2 tree
How can I query in CodeIgniter if I want to return ex. SELECT * kind WHERE id = 1 and i want to return also all the data inside living table?
Example output:
id kind_o living_id living.id type
1 dog 1 1 animal
2 tree
Try :
$this->db->select('k.*,l.type');
$this->db->from('kind as k');
$this->db->join('living as l','l.id = k.living_id');
$this->db->where('l.id','1');//use Kind id Here you want to use.
$query = $this->db->get();
$this->db->last_query();
return $query->result_array();
See Document
select k.id as kind_id, k.kind_o, k.living_id, l.id as living_id, l.type FROM kind k join living l on (k.living_id=l.id);
Always prefer to select fields comma seperated then using select *.
select * usually takes time compared to query selecting all required feilds.

Handling Multi level category structure dynamically

Currently working on the project related to Business listing. I need some help in handing category structure.
Using the table name Bus_CategoryTbl to maintain the categories & used fields are Cat_ID, Cat_Name, Cat_Slug, Cat_Level etc., In this, Cat_PID will have the Cat_ID of the parent category.
Here are the example records,
Cat_ID Cat_name Cat_Slug Cat_PID
1 Web Design web-design 0
2 PHP php 1
3 MYSQL mysql 1
4 Hotels hotels 0
5 5 Stars 5-stars 4
6 3 stars 3-stars 4
7 Le Meridian le-meridian 5
8 St Laurn Suites st-laurn-suites 5
9 Niraali Executive niraali 6
Cat_PID value 0 indicates first level parent category.
Above is the example records, above table have 3 levels. For Ex: Hotels (Cat_ID: 4) -> 5 Stars (Cat_ID: 5) -> St Laurn Suites (Cat_ID: 8)
How the acheive the above result dynamically using PHP/MySql (Levels may increased in future)? It should not utiize more CPU time. current code was written in 3 dimensional array structure using foreach, but its little confused taking more CPU time.
Can you someone help me in achieving this? TIA.
Try following code
function Fname($parentId=0){
$catgArray = array();
$sql = mysql_query("SELECT * FROM Table Where Cat_PID=$parentId");
$mainCatg = mysql_fetch_array($sql);
foreach($mainCatg as $mc){
array_push($catgArray , $mc);
$subCatg = $this->Fname($mc->Cat_ID);
if (count($subCatg ) > 0) {
array_push($catgArray , $subCatg );
}
}
return $catgArray;
}
In the Result we can check the sub category levels by using is_array() function

Store and fetch CSV columns from DB using implode and magic __get()

I have PHP code to select categories from tbl_categorie, Now I have a multiple select in a form where an article can have more than one categorie. While inserting the values in database, I want to store multiple categories values in one column/attribute. Where ID_CAT attribute would only store categories ids of the tbl_categorie separated by comma(,).
I have two tables in one DB,
tbl_blog:
ID_BLOG ID_CAT TITLE ARTICL DATE
1 1,3 title1 article1 2013-03-04
2 4,10 title2 article2 2013-03-04
3 3,6 title3 article3 2013-03-04
tbl_categorie:
ID_CAT NOM_CAT
1 HTML
2 CSS
3 DESIGN
4 PHP
5 ..
I have problem in first place to add tow ID_CAT for one article although I used the implode() statment but she works when i change the type of ID_CAT from int to varchar , and this is the process to add article :
Article::creatArticle(0,$_POST['title'],implode(', ', $_POST['id_categorie']),$_POST['article']);
and this is the function to add article from class_article :
/**
* function créeArticle
*/
public static function creatArticle($id_article,$title,$id_categorie,$article)
{
global $db;
$req = $db->prepare("INSERT INTO blog (ID_BLOG,TITLE,ID_CAT, ARTICLE,DATE) VALUES ('',:title,:id_categorie,:article,'".date('Y-m-d')."')");
$ok = $req->execute(Array('title' =>$title,'id_categorie' => $id_categorie,'article' => $article));
return $db->lastInsertId();
//$erreur = $req->errorInfo();
}
now i have probleme to fetch all categories for which in each article shall have , and this is how i fetch in my back-office the table of articles using the magic method get() which she returne only the first value in th column :
<?php
foreach(Article::getAllArticle()as $blog ){
$article= new Article($blog->ID_BLOG);
$categorie = new Categorie($article->getIDCategorie());
echo'
<tr>';
echo '<td><input type="checkbox" /></td>';
echo '<td>'.$article->getTitlearticle().'</td>';
echo '<td>'.$categorie->getNomCategorie().'</td>';
echo '<td>'.$article->getDatearticle().'</td>';
echo '<td>35</td>';
echo ' <td class="actions">';
echo '<img src="img/icons/actions/edit.png" alt="" />';
echo ' <img src="img/icons/actions/delete.png" alt="" /></td>';
echo '</tr>';
} ..
i know that i have to use the explode() statment or making a loop but i can't figure it out how :( ,and i have a doubt about the type of ID_CAT should be varchar make the problem ? thanx !
It is difficult to understand what you are doing and what you want to do. I'm not sure if you are getting the results from a CSV file or from a database?
If it is from a database, from what I can see you need to normalise your database tables. Create a linking table between the blog and categories, this would make it a lot easier to bring back the results. A simple join sql will get all articles in an category or the get all categories that the article is associated with.
tbl_blog:
ID_BLOG TITLE ARTICL DATE
1 title1 article1 2013-03-04
2 title2 article2 2013-03-04
3 title3 article3 2013-03-04
tbl_categorie:
ID_CAT NOM_CAT
1 HTML
tbl_blogcat
ID_BLOG ID_CAT
1 1
1 3
2 4
2 10
It might be a little extra work now but it will be worth it in the future. Storing your categories as a comma delimited string makes it difficult to search.
This problem can be solve easy way, You can create a new table which will store the information of tbl_blog and tbl_catagory's primary id. The benefit is when you choose one more categories of a blog it will store your information of every category of a blog. the table is look like.....
tbl_combine:
ID_COMB ID_Blog ID_Cat
1 1 2
2 1 1
3 1 3
4 2 3
5 2 2
6 3 1
7 3 2
8 3 3
Above we just let 3 blog and 3 categories. the tbl_combine can store each blog category's primary id of its chosen blog in each row. So we can insert unlimited categories of a blog. there's no need explode or implode function.
Then we can retrieve any blog categories. The query look like.
SELECT
(SELECT category_name FROM tbl_catagory
WHERE id_cat=A.id_cat)
AS catagory_name
FROM tbl_combine
AS A
WHERE id_blog=$blog_id
Note we just store id of tbl_blog and tbl_catagory tables is tbl_combine it will not slow

For each result return by SQL query I want as to give a different name

My SQL statement looks like
SELECT beds.id,beds.name,beds.brand,beds.price,beds.disprice,feature.feature AS feature
FROM beds,feature,bedFeatures
WHERE bedFeatures.featureID = feature.id AND bedFeatures.bedID = beds.id
I get this result
id name brand price disprice feature
10 Big Sleeper ZZZZ 10000 1 Oak
10 Big Sleeper ZZZZ 10000 1 Ash
10 Big Sleeper ZZZZ 10000 1 White
What I want is for the AS to give each feature a unique name such as feature1 feature2 feature3 so those 4 lines are displyaed in one. Is this possible?
The output I am looking for would look something like
id name brand price disprice feature1 feature2 feature3
10 Big Sleeper zzzz 1000 1 Oak Ash White
The exact output you request is not easily achieved, except by using GROUP_CONCAT() to list the features as a comma-separated list rather than individual columns.
Because there is not a fixed set of possible features common to all your products, you will not be able to use a pivot query.
I would recommend using GROUP_CONCAT() to retrieve the features as a comma-separated list, and then splitting them apart with PHP in your application layer.
SELECT
beds.id,
beds.name,
beds.brand,
beds.price,
beds.disprice,
GROUP_CONCAT(feature) AS features
FROM
beds
JOIN bedFeatures ON beds.id = bedFeatures.bedID
JOIN features ON features.id = bedFeatures.featureID
GROUP BY beds.id, beds.name, beds.brand, beds.price, disprice
The output of this will look like:
d name brand price disprice features
10 Big Sleeper zzzz 1000 1 Oak,Ash,White
In your PHP, when fetching the results, explode() the features into an array:
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
// First append the whole row onto the result set as it is...
$resultset[$row['id']] = $row;
// Overwrite the `features` string with an array instead...
$resultset[$row['id']]['features'] = explode(",", $row['features']);
}
Finally, access the features in your application as:
foreach ($resultset as $r) {
echo $r['features'][0];
echo $r['features'][1];
echo $r['features'][2];
echo $r['features'][3];
}
You're looking for GROUP_CONCAT.

Categories