How to display count information to page - php

I have created a query to select and count specific fields from one table and the corrisponding name from another table the query works when i run it in the sql on localhost but cant work out how to display the result to the page
e.g
Item name1 - count
tiem name2 - count
here is the query
$objects->connect();
// Count Query
$countQuery = 'SELECT a.`subId`, b.`subId`, b.`subTitle`, COUNT(a.`subId`) FROM `tbl_list`a, `tbl_subs`b WHERE a.`subId` = b.`subId` GROUP BY a.`subId`';
//Run the query
$objects->query($countQuery);
how would i display the result to the page

First your function $objects->query($countQuery); must return the result array which you can get like this:
$result = $objects->query($countQuery);
and then apply loop to $result;
Yes add COUNT(a.subId) as cnt as well and then like echo $result[0]->cnt;
depends upon your return array format.

Related

How to get the count of a specif value from a single column

I was working with a project where I want to get the count of values in a column. I will explain with an example.
I have a table column named name. Where it's values are A,B,C,D,A,D,B,A,C.
Now I want the output as
Count: A-3,B-2,C-2,D-2.
I have tried using group by and distinct. but both don't give me what I want. It all getting the total count of that item. In the code given below is the query I tried. There I want the count of particulars_id and the $public_page_id will be common for all particulars_id I am fetching. There will be a number of public_page_id in the table, and each will have some particulars_id under them.
$output = '';
$this->db->select('COUNT(service_appointment_details.particulars_id)
as count,particulars.particulars_name');
$this->db->from('particulars');
$this->db->group_by('particulars.particulars_id');
$this->db->where('particulars.public_page_id',$public_page_id);
$this->db-
>join('service_appointment_details','particulars.public_page_id =
service_appointment_details.public_page_id','right');
$this->db->where($where_date);
$query = $this->db->get();
Expected Result
Expected Result is (based on the above example)
Count: A-3,B-2,C-2,D-2.
Actual Result
But what I'm getting now is
Count: A-9,B-9,C-9,D-9.
I need to fetch count of each particulars_id under the given public_page_id
You should use count(*)
$this->db->select('COUNT(*) as count,particulars.particulars_name');
........
As pointed out by #scaisEdge, you need to use count(*) instead of count(service_appointment_details.particulars_id). By using count(service_appointment_details.particulars_id), you basically count the number of rows from your select which is not what you want.
Final snippet would be:
$output = '';
$this->db->select('COUNT(*) as count, particulars.particulars_name');
$this->db->from('particulars');
$this->db->group_by('particulars.particulars_name');
$this->db->where('particulars.public_page_id',$public_page_id);
$this->db->join('service_appointment_details','particulars.public_page_id = service_appointment_details.public_page_id','right');
$this->db->where($where_date);
$query = $this->db->get();
Whenever you want to count occurrence of a column values, you'd do
SELECT column_to_count, count(*) FROM table GROUP BY column_to_count

Special mysql call for get numbers of rows

in Wordpress/WooCommerce MySQL database i have various shortcodes.
If there is 2 orders in the database then one of the orders is a shop_order and the next one is shop_subscription_order. We find those 2 datas in another tabel by calling post_id, which is named wp_posts. There we have to look on the shop_subscription_order if the order is wc_active. We need one mySQL call that looks on how many rows there is on each customer, if there is 2 rows it has to take post_id on the subscription_order and check if it is wc_active, and print all orders with that status.
A not working example but for show what i mean:
SELECT * from post_meta where meta_key=´_customer_id´ and meta_vlaue=´$customerid´ if number of rows='2' select * from wp_post where post_type='shop_supscription' whit the id form post_meta and post_status='wc-active'
and then echo num_of_rows
video example here:
Https:// nltrading.dk/video.mov
First in the video we show an order with 3 rows, and after we show an order with 2 rows.
We only need the orders with 2 rows, where there is an wc_active as shown in the video. We need to call all of this to count the number of rows where there is an wc_active whit only 2 rows of orders.
Use this like code:
//To show number of rows in table
function test()
{
global $wpdb;
$table_name = $wpdb->prefix . 'mydata';
$count_query = "select count(*) from $table_name";
$num = $wpdb->get_var($count_query);
echo $num . 'Rows Found';
}

Get values from CSV file and search MySQL database

I have a query a Wordpress include which does the following:
$sql = "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'merchant_id' LIMIT 6";
$results = $wpdb->get_results($sql);
foreach ($results as $row)
{
echo $row->meta_value . ",";
//sprintf("SELECT * FROM retailers WHERE advertiserId = '%s'", $row->meta_value);
}
//clean all results
$wpdb->flush();
It parses all pages custom fields (merchant ID numbers), and returns any unique distinct values, separated by a comma. This bit works great.
ie: The above may return: 1301,345,723,134,1435
What I also have is a separate MySQL table of about 20 fields, three of which are the MerchantID, programmeName, and commissionMax. Each value from the CSV correlates with the MerchantID in the database.
Regardless of the amount of merchant ID's that appear in the CSV - I need to parse them all, but show the three highest commission rates (commissionMax), as well as the programmeName.
I managed to get connected to my external database and retrieve the appropriate values (using the commented code above) however this showed all of the retailers information.
Any advice?
Use the following query with limit:
SELECT * // select all fields
FROM table_name // from your table
WHERE MerchantID IN (your_ids_here) // IDs received from previous query or wherever
ORDER BY commissionMax DESC // descending sort by commissionMax field
LIMIT 3 // take first 3 results

Join query in Moodle only returns last column only while mysql returns correctly

I have 2 tables in my moodle database such as equiz_details and equiz_responses as follows:
mdl_equiz_details:
mdl_equiz_details
I have used a join query to fetch result as desired form as follows:
SELECT distinct ed.quizid,ed.questionnumber,ed.questiontext,ed.optiontext1,ed.optiontext2,ed.optiontext3,ed.optiontext4, ed.correctanswer,er.studentanswer FROM `mdl_equiz_details` as ed INNER JOIN `mdl_equiz_responses` as er ON ed.quizid = er.quizid and ed.questionnumber = er.questionnumber and er.studentid=4 and er.quizid=25
I fired the query in mysql database annd got result as follows:
Result in mysql
I am using the same query inside my moodle page and try to fetch result as follows::
<?php
require_once('../../config.php');
global $DB;
$quizresdetails = $DB->get_records_sql("SELECT ed.quizid,ed.questionnumber,ed.questiontext,ed.optiontext1,ed.optiontext2,ed.optiontext3,ed.optiontext4, ed.correctanswer,er.studentanswer FROM {equiz_details} ed INNER JOIN {equiz_responses} er ON ed.quizid = er.quizid and ed.questionnumber = er.questionnumber and er.studentid=4 and er.quizid=25");
var_dump($quizresdetails);
?>
I am getting the result as follows:
Result in Moodle page
Which is obviously the last result.
What I am doing wrong? How can I fetch full result in my moodle page?
Moodle version: 2.9.1
The problem is your query is returning the same value for its id in each record: "25". The Moodle get_records_* methods expect every result to have a unique id, as it uses that id as the array key in the array of results it returns. So it's finding all your results, but as it loops through them it is adding each result to the array key "25", so then when it gets to the end, it only has the last result in the returned array.
So you need to return a field with a unique id for each row, as "id".

SELECT a few rows out of MYSQL

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.

Categories