Need to count the number of rows for each category in a MySQL table using PDO. For example, I need to have the number of entries for category 1, category 2, etc. If possible, I would like to do this without having to write out an SQL statement for each category.
Thanks!
The SQL you need is something like:
SELECT category_name, COUNT(*) AS total FROM category_table
GROUP BY category_name
This will return a result set that has one row for each category. Each row has two columns: the category name and the total number of records with that category name. The same technique works for category id's or any other key you may want to use.
You would use it this way:
$sql = 'SELECT category_name, COUNT(*) AS total FROM category_table '.
'GROUP BY category_name';
$db = new PDO($database, $user, $password);
$results = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
// $results is now an array with the query results
Edit: added sample PHP code.
Related
I have 5 different tables in my dB with the structure Name|Price|Id..
I have a unique price and Id entry combination.
Using these 2, what could be the possible SQL query to fetch the name of the table in which this entry is present?
I need to fetch the name of this table in order to update the value of Price.
You really should normalise your database properly and use a single table, but if you really need a kludge then:
SELECT name, brand, id, 'Tea' as tablename
FROM TableTea
WHERE brand = 'abc'
AND id = 100
UNION
SELECT name, brand, id, 'Coffee' as tablename
FROM TableCoffee
WHERE brand = 'abc'
AND id = 100
UNION
SELECT name, brand, id, 'Chocolate' as tablename
FROM TableChocolate
WHERE brand = 'abc'
AND id = 100
And you'll have to change it if you ever add new products
if your DBMS is MySQL you can use this Query:
SELECT Result.TABLE_NAME FROM (
SELECT TABLE_NAME,COLUMN_NAME,COUNT(*) AS QTA FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'NAME_DB'
and COLUMN_NAME IN ('Name','Price','Id')
GROUP BY TABLE_NAME
) as Result
WHERE Result.QTA = 3
i have already tried to do without php
Replace NAME_DB with your Database.
You would first need to know the tables in which it's possible to have the entry. Use a loop to iterate over those tables and run the query, each time returning a result set and testing if records exist in the result set. This will tell you what tables have the entry.
General Approach:
$array = array("table1", "table2", "table3", "table4", "table5");
foreach($array as $table) {
//build your query using the table name
$query = "SELECT something FROM " . $table;
//exec your query against your db and return results
//test if records exist in result set. If true, you know the table name based on the loop iteration ($table).
}
Here is my query.
$request = "SELECT
required_items.id,
required_items.name,
required_items.required_amount AS Amount_Required,
COALESCE(SUM(donations.donation_amount),0) AS Amount_Donated
FROM required_items
LEFT JOIN donations ON donations.item_id=required_items.id
GROUP BY item_id ASC";
$stmt = $db->query($request);
$item_info = $stmt->fetchAll();
I am only receiving three of the five items in my "required_items" database. I intend for this to fetch all of them. What can I be doing wrong? I'm stumped.
Upon further testing I noticed the items are not being grouped with"item_id" in ascending order.
EDIT:
Here's my fiddle for this problem:
http://sqlfiddle.com/#!9/7afc3/1/0
The intended results would be to list all five items in the database in the manner they are displayed with the query, instead of just three.
EDIT: I was grouping by a column in the wrong table! "item_id" needed to be changed to "required_items.id".
You are grouping on a table that has only 3 rows selected (two with values and one null), you could use the field from the other table:
$request = "SELECT
required_items.id,
required_items.name,
required_items.required_amount AS Amount_Required,
COALESCE(SUM(donations.donation_amount),0) AS Amount_Donated
FROM required_items
LEFT JOIN donations ON donations.item_id=required_items.id
GROUP BY required_items.id ASC"; // <- MODIFIED HERE
$stmt = $db->query($request);
$item_info = $stmt->fetchAll();
I have the following query.
$sql = "SELECT customer FROM furniture WHERE id = :id AND category = :cat";
$stmt = $connectdb->prepare($sql);
$stmt->execute(array(':id'=>$id, ':cat'=>"1"));
$resulta = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowcount = count($result);
This works perfectly. But I have a requirement to get the number of rows from WHERE id = :id AND category = :cat as well as to get the number of rows from WHERE category = :cat. Is it possible to do both of them without having to write all those SELECT query lines twice?
You can use conditional sum to get the 2 different counts something as
select
sum(id = :id AND category = :cat) as count1,
sum(category = :cat) as count2
from furniture;
Later you just fetch the records and get the values of count1 and count2
NOTE : If you just do row count it will always return 1 since its using the aggregate function
I would suggest that you write the query as:
select sum(id = :id) as numCatId, count(*) as numCat
from furniture
where cat = :cat;
Putting the condition in the where clause allows MySQL to use an index on furniture(cat) (or better yet furniture(cat, id). In general, it is a good idea to put common filtering conditions in the where clause. This reduces the number of rows needed for processing the rest of the query.
I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}
I need to select category ids from my sql database.
I have a variable $product_id and for each product id there are three rows in a table that i need to select using PHP.
If I do "SELECT * FROM table_name WHERE product_id='$prodid'"; I only get the one on the top.
How can I select all three category_ids which contain the same product_id?
I suppose you are using PHP's mysql functions, is this correct? I am figuring that your query is actually returning all three rows but you aren't fetching all of them.
$sql = "SELECT * FROM table_name WHERE product_id='$prodid'";
$r = mysql_query($sql, $conn); //where $conn is your connection
$x = mysql_fetch_SOMETHING($r); //where something is array, assoc, object, etc.
The fetch function gives only one row at a time. You say you need three so it needs to be executed three times.
$x[0] = mysql_fetch_assoc($r);
$x[1] = mysql_fetch_assoc($r);
$x[2] = mysql_fetch_assoc($r);
OR this would be better
while($curRow = mysql_fetch_assoc($r)) //this returns false when its out of rows, returns false
{
$categoryIds[] = $curRow['category_id'];
}
If this doesn't do it then your query is actually returning only one row and we need to see your tables/fields and maybe sample data.
SQL seems to be correct, but Why do you store product_id in categories table? if it's one-to-many relation it would be better to store only category_id in products table.
The SQL query is correct for what you want to do. It will select all the records in table_name with the field product_id = $prodid (not only 1 or 3 but any that matches the variable)
To select a few records you should use the LIMIT keyword
You should look inside your table structure and the variable $prodid to find problems.